View | Details | Raw Unified | Return to bug 239979 | Differences between
and this patch

Collapse All | Expand All

(-)schema/midletTemplateWizard.exsd (+163 lines)
Line 0 Link Here
1
<?xml version='1.0' encoding='UTF-8'?>
2
<!-- Schema file written by PDE -->
3
<schema targetNamespace="org.eclipse.mtj.ui">
4
<annotation>
5
      <appInfo>
6
         <meta.schema plugin="org.eclipse.mtj.ui" id="midletTemplateWizard" name="Midlet Template Wizard"/>
7
      </appInfo>
8
      <documentation>
9
         Provides an extension point for registering an Midlet Template Wizard. User can create a Midlet from a Midlet Template Wizard.
10
      </documentation>
11
   </annotation>
12
13
   <element name="extension">
14
      <complexType>
15
         <sequence minOccurs="1" maxOccurs="unbounded">
16
            <element ref="wizard" minOccurs="1" maxOccurs="unbounded"/>
17
         </sequence>
18
         <attribute name="point" type="string" use="required">
19
            <annotation>
20
               <documentation>
21
                  
22
               </documentation>
23
            </annotation>
24
         </attribute>
25
         <attribute name="id" type="string">
26
            <annotation>
27
               <documentation>
28
                  
29
               </documentation>
30
            </annotation>
31
         </attribute>
32
         <attribute name="name" type="string">
33
            <annotation>
34
               <documentation>
35
                  
36
               </documentation>
37
               <appInfo>
38
                  <meta.attribute translatable="true"/>
39
               </appInfo>
40
            </annotation>
41
         </attribute>
42
      </complexType>
43
   </element>
44
45
   <element name="wizard">
46
      <complexType>
47
         <sequence>
48
            <element ref="description" minOccurs="0" maxOccurs="1"/>
49
         </sequence>
50
         <attribute name="id" type="string" use="required">
51
            <annotation>
52
               <documentation>
53
                  a unique name that will be used to identify this wizard.
54
               </documentation>
55
            </annotation>
56
         </attribute>
57
         <attribute name="name" type="string" use="required">
58
            <annotation>
59
               <documentation>
60
                  a translatable name that will be used in UI representation
61
of this wizard.
62
               </documentation>
63
               <appInfo>
64
                  <meta.attribute translatable="true"/>
65
               </appInfo>
66
            </annotation>
67
         </attribute>
68
         <attribute name="class" type="string" use="required">
69
            <annotation>
70
               <documentation>
71
                  a fully qualified name of a class. The class must extends &lt;samp&gt;org.eclipse.mtj.ui.template.MidletTemplateWizard&lt;/samp&gt;
72
               </documentation>
73
               <appInfo>
74
                  <meta.attribute kind="java" basedOn="org.eclipse.mtj.ui.template.MidletTemplateWizard:"/>
75
               </appInfo>
76
            </annotation>
77
         </attribute>
78
         <attribute name="icon" type="string">
79
            <annotation>
80
               <documentation>
81
                  a relative path of an icon that will be used to visually 
82
represent the wizard.
83
               </documentation>
84
               <appInfo>
85
                  <meta.attribute kind="resource"/>
86
               </appInfo>
87
            </annotation>
88
         </attribute>
89
      </complexType>
90
   </element>
91
92
   <element name="description" type="string">
93
      <annotation>
94
         <appInfo>
95
            <meta.element translatable="true"/>
96
         </appInfo>
97
         <documentation>
98
            Short description of this wizard.
99
         </documentation>
100
      </annotation>
101
   </element>
102
103
   <annotation>
104
      <appInfo>
105
         <meta.section type="since"/>
106
      </appInfo>
107
      <documentation>
108
         [Enter the first release in which this extension point appears.]
109
      </documentation>
110
   </annotation>
111
112
   <annotation>
113
      <appInfo>
114
         <meta.section type="examples"/>
115
      </appInfo>
116
      <documentation>
117
         &lt;extension
118
       point=&quot;org.eclipse.mtj.ui.midletTemplateWizard&quot;&gt;
119
    &lt;wizard
120
          class=&quot;org.eclipse.mtj.examples.midlettemplate.helloworld.HelloWorldMidletTemplateWizard&quot;
121
          icon=&quot;icons/class_obj_green.gif&quot;
122
          id=&quot;org.eclipse.mtj.ui.templateWizard.helloWorld&quot;
123
          name=&quot;Hello World Midlet Template&quot;&gt;
124
       &lt;description&gt;
125
          Hello world Midlet template. This template is just a example template which demonstrate how to create a Midlet template. You may create your own template by mimicing this example.
126
       &lt;/description&gt;
127
    &lt;/wizard&gt;
128
 &lt;/extension&gt;
129
      </documentation>
130
   </annotation>
131
132
   <annotation>
133
      <appInfo>
134
         <meta.section type="apiInfo"/>
135
      </appInfo>
136
      <documentation>
137
         The class attribute specified a class must extend &lt;samp&gt;org.eclipse.mtj.ui.template.MidletTemplateWizard&lt;/samp&gt; class.
138
      </documentation>
139
   </annotation>
140
141
   <annotation>
142
      <appInfo>
143
         <meta.section type="implementation"/>
144
      </appInfo>
145
      <documentation>
146
         [Enter information about supplied implementation of this extension point.]
147
      </documentation>
148
   </annotation>
149
150
   <annotation>
151
      <appInfo>
152
         <meta.section type="copyright"/>
153
      </appInfo>
154
      <documentation>
155
         Copyright (c) 2008 Sybase Inc. and others.&lt;br&gt;
156
All rights reserved. This program and the accompanying materials
157
are made available under the terms of the Eclipse Public License v1.0
158
which accompanies this distribution, and is available at &lt;a 
159
href=&quot;http://www.eclipse.org/legal/epl-v10.html&quot;&gt;http://www.eclipse.org/legal/epl-v10.html&lt;/a&gt;
160
      </documentation>
161
   </annotation>
162
163
</schema>
(-)plugin.xml (+12 lines)
Lines 4-9 Link Here
4
   <extension-point id="deviceEditor" name="Device Editor" schema="schema/org_eclipse_mtj_ui_deviceEditor.exsd"/>
4
   <extension-point id="deviceEditor" name="Device Editor" schema="schema/org_eclipse_mtj_ui_deviceEditor.exsd"/>
5
   <extension-point id="jadAttributes" name="JAD Attributes" schema="schema/jadAttributes.exsd"/>
5
   <extension-point id="jadAttributes" name="JAD Attributes" schema="schema/jadAttributes.exsd"/>
6
   <extension-point id="jadEditorPages" name="JAD Editor Pages" schema="schema/jadEditorPages.exsd"/>
6
   <extension-point id="jadEditorPages" name="JAD Editor Pages" schema="schema/jadEditorPages.exsd"/>
7
   <extension-point id="midletTemplateWizard" name="Midlet Template Wizard" schema="schema/midletTemplateWizard.exsd"/>
7
   <extension
8
   <extension
8
         point="org.eclipse.ui.newWizards">
9
         point="org.eclipse.ui.newWizards">
9
      <category
10
      <category
Lines 35-40 Link Here
35
            %wizard.newMidlet.description
36
            %wizard.newMidlet.description
36
         </description>
37
         </description>
37
      </wizard>
38
      </wizard>
39
      <wizard
40
            category="mtj.category"
41
            class="org.eclipse.mtj.ui.internal.wizards.template.NewMidletFromTemplateWizard"
42
            finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
43
            icon="icons/newclass_wiz_green.gif"
44
            id="org.eclipse.mtj.ui.wizards.NewMidletFromTemplateWizard"
45
            name="%wizard.newTemplateMidlet.label">
46
         <description>
47
            %wizard.newTemplateMidlet.description
48
         </description>
49
      </wizard>
38
   </extension>
50
   </extension>
39
   <extension
51
   <extension
40
         point="org.eclipse.ui.importWizards">
52
         point="org.eclipse.ui.importWizards">
(-)META-INF/MANIFEST.MF (+1 lines)
Lines 41-44 Link Here
41
Bundle-ManifestVersion: 2
41
Bundle-ManifestVersion: 2
42
Export-Package: org.eclipse.mtj.ui.devices,
42
Export-Package: org.eclipse.mtj.ui.devices,
43
 org.eclipse.mtj.ui.jadEditor,
43
 org.eclipse.mtj.ui.jadEditor,
44
 org.eclipse.mtj.ui.template,
44
 org.eclipse.mtj.ui.viewers
45
 org.eclipse.mtj.ui.viewers
(-)plugin.properties (+3 lines)
Lines 61-66 Link Here
61
wizard.newMidlet.label=Java ME MIDlet
61
wizard.newMidlet.label=Java ME MIDlet
62
wizard.newMidlet.description=Create a Java ME MIDlet
62
wizard.newMidlet.description=Create a Java ME MIDlet
63
63
64
wizard.newTemplateMidlet.label=Java ME MIDlet from Template
65
wizard.newTemplateMidlet.description=Create a Java ME MIDlet from a Template
66
64
importWizards.EclipseMEProject.label=Import EclipseME Project
67
importWizards.EclipseMEProject.label=Import EclipseME Project
65
importWizards.EclipseMEProject.description=Select a directory to search for existing EclipseME projects.
68
importWizards.EclipseMEProject.description=Select a directory to search for existing EclipseME projects.
66
#
69
#
(-)src/org/eclipse/mtj/ui/template/MidletTemplate.java (+147 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
package org.eclipse.mtj.ui.template;
13
14
import java.util.ArrayList;
15
import java.util.List;
16
17
import org.eclipse.mtj.ui.internal.template.TemplateMessages;
18
19
/**
20
 * You can subclass this class to create your own template class.
21
 * 
22
 * @author wangf
23
 * 
24
 */
25
public abstract class MidletTemplate {
26
	/**
27
	 * The name of the folder that contains Midlet template. We recommend you
28
	 * create a folder with this name under project root, and put your templates
29
	 * into it. For example, your template path may like this:
30
	 * /%PROJECT_ROOT%/templates/helloWorldTemplate/
31
	 */
32
	public static final String TEMPLATE_FOLDER = "templates";
33
	/**
34
	 * The name of the folder which located in the template folder. All your
35
	 * Java Source template should be put into this folder. The folder name MUST
36
	 * be "java". For example, your java source template folder may like this:
37
	 * /%PROJECT_ROOT%/templates/helloWorldTemplate/java/
38
	 */
39
	public static final String JAVA_FOLDER = "java";
40
	/**
41
	 * The name of the folder which located in the template folder. All your
42
	 * resource file should be put into this folder. The folder name MUST be
43
	 * "resource". For example, your resource file folder may like this:
44
	 * /%PROJECT_ROOT%/templates/helloWorldTemplate/resource/
45
	 */
46
	public static final String RESOURCE_FOLDER = "resource";
47
	/**
48
	 * Every java source template need a package declaration. The package
49
	 * declaration appear like this:
50
	 * <p>
51
	 * package $packageName$;
52
	 * </p>
53
	 * $packageName$ will be replaced with the real package name.
54
	 * 
55
	 */
56
	public static final String OPTION_PACKAGE = "packageName";
57
	/**
58
	 * The list store all template options.
59
	 */
60
	private List<TemplateOption> options;
61
62
	public MidletTemplate() {
63
		options = new ArrayList<TemplateOption>();
64
		// The default value of "packageName" option is
65
		// {@link TemplateMessages.Option_Package_defaultValue}.
66
		// You may change the value in the subclass is you don't like it.
67
		options.add(new StringOption(OPTION_PACKAGE,
68
				TemplateMessages.Option_Package_label,
69
				TemplateMessages.Option_Package_defaultValue));
70
	}
71
72
	/**
73
	 * Get the substitute string for template option. It's default behavior is
74
	 * to return TemplateOption.getValue().toString().
75
	 * 
76
	 * @param optionName
77
	 *            - the name of the template option.
78
	 * @return - the substitute string of the template option.
79
	 */
80
	public String getSubstituteStringFor(String optionName) {
81
		TemplateOption option = getOption(optionName);
82
		if (option != null) {
83
			return option.getValue().toString();
84
		} else {
85
			return "";
86
		}
87
	}
88
89
	/**
90
	 * Get a list contains all the options.
91
	 * 
92
	 * @return
93
	 */
94
	public List<TemplateOption> getOptions() {
95
		return options;
96
	}
97
98
	/**
99
	 * Get a option by it's name.
100
	 * 
101
	 * @param optionName
102
	 * @return
103
	 */
104
	public TemplateOption getOption(String optionName) {
105
		List<TemplateOption> options = getOptions();
106
		int i = options.indexOf(new StringOption(optionName, null, null));
107
		if (i >= 0) {
108
			TemplateOption option = options.get(i);
109
			return option;
110
		} else {
111
			return null;
112
		}
113
	}
114
115
	/**
116
	 * Add a template option.
117
	 * 
118
	 * @param option
119
	 */
120
	protected void addOption(TemplateOption option) {
121
		options.add(option);
122
	}
123
124
	/**
125
	 * Return the path string of the Midlet icon. This path will be added in to
126
	 * the JAD file. For example, if this method return a String
127
	 * "/icons/myIcon.gif", your Midlet declaration in the JAD may like this:
128
	 * <p>
129
	 * <code>MIDlet-1: MyTemplateMidlet,/icons/myIcon.gif,myj2meapp.helloworld.MyTemplateMidlet</code>
130
	 * </p>
131
	 * You may override this method to provide a icon for your template Midlet.
132
	 * 
133
	 * @return - a string stand for the path of the icon for the Midlet
134
	 */
135
	protected String getMidletIconPath() {
136
		return "";
137
	}
138
139
	/**
140
	 * Get the name of the Midlet template. This name will display as the title
141
	 * of the wizard page.
142
	 * 
143
	 * @return
144
	 */
145
	public abstract String getName();
146
147
}
(-)src/org/eclipse/mtj/ui/template/MidletTemplateWizard.java (+686 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
package org.eclipse.mtj.ui.template;
13
14
import java.io.File;
15
import java.io.FileInputStream;
16
import java.io.FileNotFoundException;
17
import java.io.FileOutputStream;
18
import java.io.IOException;
19
import java.io.InputStream;
20
import java.io.InputStreamReader;
21
import java.io.OutputStreamWriter;
22
import java.io.Reader;
23
import java.io.UnsupportedEncodingException;
24
import java.lang.reflect.InvocationTargetException;
25
import java.net.URL;
26
import java.util.Enumeration;
27
import java.util.HashMap;
28
import java.util.Map;
29
import java.util.regex.Matcher;
30
import java.util.regex.Pattern;
31
import java.util.zip.ZipEntry;
32
import java.util.zip.ZipFile;
33
34
import org.eclipse.core.resources.IFile;
35
import org.eclipse.core.resources.IResource;
36
import org.eclipse.core.resources.IWorkspaceRoot;
37
import org.eclipse.core.resources.ResourcesPlugin;
38
import org.eclipse.core.runtime.CoreException;
39
import org.eclipse.core.runtime.FileLocator;
40
import org.eclipse.core.runtime.IPath;
41
import org.eclipse.core.runtime.IProgressMonitor;
42
import org.eclipse.core.runtime.IStatus;
43
import org.eclipse.core.runtime.Path;
44
import org.eclipse.core.runtime.SafeRunner;
45
import org.eclipse.jdt.core.ICompilationUnit;
46
import org.eclipse.jdt.core.IJavaElement;
47
import org.eclipse.jdt.core.IJavaProject;
48
import org.eclipse.jdt.core.IPackageFragmentRoot;
49
import org.eclipse.jdt.core.IType;
50
import org.eclipse.jdt.core.JavaCore;
51
import org.eclipse.jface.operation.IRunnableWithProgress;
52
import org.eclipse.jface.wizard.Wizard;
53
import org.eclipse.mtj.core.internal.MTJCorePlugin;
54
import org.eclipse.mtj.core.internal.utils.Utils;
55
import org.eclipse.mtj.core.model.jad.ApplicationDescriptor;
56
import org.eclipse.mtj.core.model.project.IMidletSuiteProject;
57
import org.eclipse.mtj.core.model.project.MidletSuiteFactory;
58
import org.eclipse.mtj.ui.internal.template.MidletTemplateWizardPage;
59
import org.eclipse.mtj.ui.internal.template.TemplateMessages;
60
import org.eclipse.mtj.ui.internal.utils.LogAndDisplaySafeRunnable;
61
import org.eclipse.mtj.ui.internal.wizards.template.TemplateWizardMessages;
62
63
/**
64
 * You should subclass this class to create your MidletTemplateWizard. You
65
 * should
66
 * <p>
67
 * 1. Provide a MidletTemplate by override {@link #createTemplate()} method
68
 * <p>
69
 * 2. Provide the URL of your template by override
70
 * {@link #getTemplateFolderURL()}
71
 * <p>
72
 * Typically you do not need add any more page to this wizard.
73
 * 
74
 * @author wangf
75
 * 
76
 */
77
public abstract class MidletTemplateWizard extends Wizard {
78
79
	private MidletTemplate template;
80
	private Pattern SUBSTITUTION_PATTERN = Pattern.compile("\\$.+?\\$");
81
	/**
82
	 * The Java source folder of your MTJ Midlet Suite project. You can choose
83
	 * it on the wizard page.
84
	 */
85
	private IPackageFragmentRoot javaRoot;
86
	/**
87
	 * The resource folder of your MTJ Midlet Suite project. You can choose it
88
	 * on the wizard page.
89
	 */
90
	private IPackageFragmentRoot resourceRoot;
91
92
	public MidletTemplateWizard() {
93
		this.template = createTemplate();
94
		setWindowTitle(TemplateMessages.MidletTemplateWizard_title);
95
		setNeedsProgressMonitor(true);
96
	}
97
98
	@Override
99
	public void addPages() {
100
		MidletTemplateWizardPage page = new MidletTemplateWizardPage(template);
101
		addPage(page);
102
	}
103
104
	@Override
105
	public boolean performFinish() {
106
		boolean completed = true;
107
108
		IRunnableWithProgress runable = getCreateMidletOperation();
109
		try {
110
			getContainer().run(false, true, runable);
111
		} catch (InvocationTargetException e) {
112
			MTJCorePlugin.log(IStatus.ERROR, e);
113
			completed = false;
114
		} catch (InterruptedException e) {
115
			MTJCorePlugin.log(IStatus.ERROR, e);
116
			completed = false;
117
		}
118
119
		return completed;
120
	}
121
122
	/**
123
	 * Set the Java source folder of your MTJ Midlet Suite project. User can
124
	 * choose the folder on the wizard page.
125
	 * 
126
	 * @param javaRoot
127
	 */
128
	public void setJavaRoot(IPackageFragmentRoot javaRoot) {
129
		this.javaRoot = javaRoot;
130
	}
131
132
	/**
133
	 * Set the resource folder of your MTJ Midlet Suite project. User can choose
134
	 * it on the wizard page.
135
	 * 
136
	 * @param resourceRoot
137
	 */
138
	public void setResourceRoot(IPackageFragmentRoot resourceRoot) {
139
		this.resourceRoot = resourceRoot;
140
	}
141
142
	/**
143
	 * Return a IRunnableWithProgress that will run in the
144
	 * {@link #performFinish()} method. This runnable create the Midlet from
145
	 * template.
146
	 * 
147
	 * @return
148
	 */
149
	private IRunnableWithProgress getCreateMidletOperation() {
150
		IRunnableWithProgress runnable = null;
151
152
		URL templateFolderURL = getTemplateFolderURL();
153
		try {
154
			templateFolderURL = FileLocator.resolve(templateFolderURL);
155
			templateFolderURL = FileLocator.toFileURL(templateFolderURL);
156
		} catch (IOException e) {
157
			return null;
158
		}
159
		if ("file".equals(templateFolderURL.getProtocol())) { //$NON-NLS-1$
160
			runnable = getDirCopyRunable(templateFolderURL);
161
		} else if ("jar".equals(templateFolderURL.getProtocol())) { //$NON-NLS-1$
162
			runnable = getZipCopyRunable(templateFolderURL);
163
		}
164
165
		return runnable;
166
	}
167
168
	/**
169
	 * Get a IRunnableWithProgress which perform the operation that copy
170
	 * templates from a jar file.
171
	 * 
172
	 * @param jarURL
173
	 *            - the URL of the Jar file which contains template.
174
	 * @return
175
	 */
176
	private IRunnableWithProgress getZipCopyRunable(URL jarURL) {
177
		final String file = jarURL.getFile();
178
		final int exclamation = file.indexOf('!');
179
		if (exclamation < 0) {
180
			return null;
181
		}
182
		IRunnableWithProgress runnable = new IRunnableWithProgress() {
183
184
			public void run(IProgressMonitor monitor)
185
					throws InvocationTargetException, InterruptedException {
186
				SafeRunner.run(new LogAndDisplaySafeRunnable(getShell(),
187
						TemplateWizardMessages.ErrorDialogTitle_duringCopy) {
188
189
					public void run() throws Exception {
190
						URL fileUrl = new URL(file.substring(0, exclamation));
191
						File pluginJar = new File(fileUrl.getFile());
192
						String templateDir = file.substring(exclamation + 1);
193
						IPath templatePath = new Path(templateDir);
194
						ZipFile zipFile = null;
195
						try {
196
							zipFile = new ZipFile(pluginJar);
197
							generateFilesFromZip(zipFile, templatePath);
198
						} finally {
199
							if (zipFile != null) {
200
								zipFile.close();
201
							}
202
						}
203
					}
204
205
				});
206
207
			}
208
209
		};
210
		return runnable;
211
	}
212
213
	/**
214
	 * Generate Midlet files including Java source code and resource files from
215
	 * jar file.
216
	 * 
217
	 * @param zipFile
218
	 * @param templatePath
219
	 * @throws CoreException
220
	 * @throws IOException
221
	 */
222
	private void generateFilesFromZip(ZipFile zipFile, IPath templatePath)
223
			throws IOException, CoreException {
224
		Map<IPath, ZipEntry>[] entryMaps = collectJavaAndResourceEntries(
225
				zipFile, templatePath);
226
227
		Map<IPath, ZipEntry> javaEntries = entryMaps[0];
228
		copyAndModifyJavaTemplateFromZip(zipFile, javaEntries);
229
230
		Map<IPath, ZipEntry> resourceEntries = entryMaps[1];
231
		copyResoueceFromZip(zipFile, resourceEntries);
232
	}
233
234
	/**
235
	 * Return a array contains 2 maps. The first map contains all the Java
236
	 * source file template ZIP entries. The second map contains all the
237
	 * resource file ZIP entries.
238
	 * 
239
	 * @param zipFile
240
	 * @param templatePath
241
	 * @return
242
	 */
243
	private Map<IPath, ZipEntry>[] collectJavaAndResourceEntries(
244
			ZipFile zipFile, IPath templatePath) {
245
		IPath javaPath = templatePath.append(MidletTemplate.JAVA_FOLDER);
246
		IPath resourcePath = templatePath
247
				.append(MidletTemplate.RESOURCE_FOLDER);
248
249
		Map<IPath, ZipEntry> javaEntries = new HashMap<IPath, ZipEntry>();
250
		Map<IPath, ZipEntry> resourceEntries = new HashMap<IPath, ZipEntry>();
251
252
		for (Enumeration<?> zipEntries = zipFile.entries(); zipEntries
253
				.hasMoreElements();) {
254
			ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
255
			IPath entryPath = new Path(zipEntry.getName());
256
			if (javaPath.isPrefixOf(entryPath) && !zipEntry.isDirectory()) {
257
				IPath key = entryPath.removeFirstSegments(javaPath
258
						.segmentCount());
259
				javaEntries.put(key, zipEntry);
260
			} else if (resourcePath.isPrefixOf(entryPath)
261
					&& !zipEntry.isDirectory()) {
262
				IPath key = entryPath.removeFirstSegments(resourcePath
263
						.segmentCount());
264
				resourceEntries.put(key, zipEntry);
265
			}
266
		}
267
		@SuppressWarnings("unchecked")
268
		// Do NOT change the sequence of the 2 element
269
		Map<IPath, ZipEntry>[] entryMaps = new Map[] { javaEntries,
270
				resourceEntries };
271
		return entryMaps;
272
	}
273
274
	/**
275
	 * Get a IRunnableWithProgress which perform the operation that copy
276
	 * templates from a folder.
277
	 * 
278
	 * @param templateFolderURL
279
	 *            - The URL of the folder which contains template.
280
	 * @return
281
	 */
282
	private IRunnableWithProgress getDirCopyRunable(URL templateFolderURL) {
283
		File templateDirectory = new File(templateFolderURL.getFile());
284
		if (!templateDirectory.exists())
285
			return null;
286
		final File javaTemplateDir = new File(templateDirectory,
287
				MidletTemplate.JAVA_FOLDER);
288
		final File resourceFileDir = new File(templateDirectory,
289
				MidletTemplate.RESOURCE_FOLDER);
290
291
		IRunnableWithProgress runnable = new IRunnableWithProgress() {
292
293
			public void run(final IProgressMonitor monitor)
294
					throws InvocationTargetException, InterruptedException {
295
				SafeRunner.run(new LogAndDisplaySafeRunnable(getShell(),
296
						TemplateWizardMessages.ErrorDialogTitle_duringCopy) {
297
298
					public void run() throws Exception {
299
						// Do copy
300
						copyAndModifyJavaTemplateFromDir(javaTemplateDir,
301
								getMidletProjectPackageFolder(), monitor);
302
						copyResourceFromDir(resourceFileDir, monitor);
303
						// refresh
304
						javaRoot.getResource().refreshLocal(
305
								IResource.DEPTH_INFINITE, monitor);
306
						resourceRoot.getResource().refreshLocal(
307
								IResource.DEPTH_INFINITE, monitor);
308
					}
309
310
				});
311
			}
312
313
		};
314
		return runnable;
315
	}
316
317
	/**
318
	 * Copy & substitute template string of all Java template ZIP entries from
319
	 * jar file. And then add Midlet declaration into JAD.
320
	 * 
321
	 * @param zipFile
322
	 *            - Jar file contains templates.
323
	 * @param javaEntries
324
	 *            - a map contains all the Java template ZIP entries.
325
	 * @throws UnsupportedEncodingException
326
	 * @throws IOException
327
	 * @throws FileNotFoundException
328
	 * @throws CoreException
329
	 */
330
	private void copyAndModifyJavaTemplateFromZip(ZipFile zipFile,
331
			Map<IPath, ZipEntry> javaEntries)
332
			throws UnsupportedEncodingException, IOException,
333
			FileNotFoundException, CoreException {
334
		for (IPath key : javaEntries.keySet()) {
335
			// Get StringBuffer before template substituting
336
			StringBuffer sb = getSbBeforeSubstituteTemplates(zipFile
337
					.getInputStream(javaEntries.get(key)));
338
			// Get StringBuffer before template substituting
339
			sb = getSbAfterSubstituteTemplates(sb);
340
			// Get the absolute path of the destination file.
341
			IPath destFilePath = getMidletProjectPackagePath().append(key);
342
			String destFileName = substituteJavaTemplateFileName(destFilePath
343
					.lastSegment());
344
			destFilePath = destFilePath.removeLastSegments(1).append(
345
					destFileName);
346
			// Do file writing
347
			writeFile(new File(destFilePath.toOSString()), sb);
348
			// Must refresh local before add Midlet declaration to JAD
349
			javaRoot.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
350
			// Add Midlet declaration to JAD
351
			addMidletToJAD(destFilePath.toFile(), null);
352
		}
353
	}
354
355
	/**
356
	 * Copy & substitute template string of all Java template files from a
357
	 * directory contains templates. And then add Midlet declaration into JAD.
358
	 * 
359
	 * @param source
360
	 * @param destination
361
	 * @param monitor
362
	 * @throws IOException
363
	 * @throws CoreException
364
	 */
365
	private void copyAndModifyJavaTemplateFromDir(File source,
366
			File destination, IProgressMonitor monitor) throws IOException,
367
			CoreException {
368
		if (source.exists() && source.isDirectory()) {
369
			destination.mkdirs();
370
371
			File[] sources = source.listFiles();
372
			for (int i = 0; i < sources.length; i++) {
373
				File currentSrc = sources[i];
374
				String currentDestName = substituteJavaTemplateFileName(currentSrc
375
						.getName());
376
				File currentDest = new File(destination, currentDestName);
377
378
				if (currentSrc.isDirectory()) {
379
					copyAndModifyJavaTemplateFromDir(currentSrc, currentDest,
380
							monitor);
381
				} else {
382
					StringBuffer sb = getSbBeforeSubstituteTemplates(new FileInputStream(
383
							currentSrc));
384
					sb = getSbAfterSubstituteTemplates(sb);
385
					writeFile(currentDest, sb);
386
					// Must refresh local before add Midlet declaration to JAD
387
					javaRoot.getResource().refreshLocal(
388
							IResource.DEPTH_INFINITE, monitor);
389
					// Add Midlet declaration to JAD
390
					addMidletToJAD(currentDest, monitor);
391
				}
392
			}
393
		}
394
	}
395
396
	/**
397
	 * Copy all of the resource files from Jar file to MTJ Midlet suite project
398
	 * resource folder.
399
	 * 
400
	 * @param zipFile
401
	 *            - the Jar file contains templates
402
	 * @param resourceEntries
403
	 *            - a map contains all the resource ZIP entries.
404
	 * @throws IOException
405
	 * @throws CoreException
406
	 */
407
	private void copyResoueceFromZip(ZipFile zipFile,
408
			Map<IPath, ZipEntry> resourceEntries) throws IOException,
409
			CoreException {
410
		for (IPath key : resourceEntries.keySet()) {
411
			InputStream in = zipFile.getInputStream(resourceEntries.get(key));
412
			IPath destFilePath = getMidletProjectResourcePath().append(key);
413
			writeFile(destFilePath, in);
414
			resourceRoot.getResource().refreshLocal(IResource.DEPTH_INFINITE,
415
					null);
416
		}
417
	}
418
419
	/**
420
	 * Copy all of the resource files from template resource directory to MTJ
421
	 * Midlet suite project resource folder.
422
	 * 
423
	 * @param resourceDir
424
	 *            - Directory contains template resource files.
425
	 * @param monitor
426
	 * @throws IOException
427
	 */
428
	private void copyResourceFromDir(File resourceDir, IProgressMonitor monitor)
429
			throws IOException {
430
		Utils.copyDirectory(resourceDir, getMidletProjectResourceDir(), null);
431
	}
432
433
	/**
434
	 * Get the Java package folder of the MTJ Midlet Suite Project.
435
	 * 
436
	 * @return
437
	 */
438
	private File getMidletProjectPackageFolder() {
439
		IPath packagePath = getMidletProjectPackagePath();
440
		File packageDir = packagePath.toFile();
441
		return packageDir;
442
	}
443
444
	/**
445
	 * Get the Java package path of the MTJ Midlet Suite Project.
446
	 * 
447
	 * @return
448
	 */
449
	private IPath getMidletProjectPackagePath() {
450
		IPath srcPath = getMidletProjectSrcPath();
451
		String packageName = template
452
				.getSubstituteStringFor(MidletTemplate.OPTION_PACKAGE);
453
		IPath packagePath = srcPath.append(packageName.replace(".", "/"));//$NON-NLS-1$
454
		return packagePath;
455
	}
456
457
	/**
458
	 * Get the path of the MTJ Midlet Suite project Source folder.
459
	 * 
460
	 * @return
461
	 */
462
	private IPath getMidletProjectSrcPath() {
463
		IPath srcPath = null;
464
		srcPath = javaRoot.getResource().getLocation();
465
		return srcPath;
466
	}
467
468
	/**
469
	 * Get the MTJ Midlet Suite project resource folder.
470
	 * 
471
	 * @return
472
	 */
473
	private File getMidletProjectResourceDir() {
474
		IPath resourcePath = getMidletProjectResourcePath();
475
		return resourcePath.toFile();
476
	}
477
478
	/**
479
	 * Get the MTJ Midlet Suite project resource path.
480
	 * 
481
	 * @return
482
	 */
483
	private IPath getMidletProjectResourcePath() {
484
		IPath resourcePath = resourceRoot.getResource().getLocation();
485
		return resourcePath;
486
	}
487
488
	/**
489
	 * Write a StringBuffer to a file.
490
	 * 
491
	 * @param destFile
492
	 *            - the destination file.
493
	 * @param sb
494
	 *            - the StringBuffer to be written to the destination file.
495
	 * @throws FileNotFoundException
496
	 * @throws UnsupportedEncodingException
497
	 * @throws IOException
498
	 */
499
	private void writeFile(File destFile, StringBuffer sb)
500
			throws FileNotFoundException, UnsupportedEncodingException,
501
			IOException {
502
		// Make necessary Dirs
503
		IPath path = new Path(destFile.getPath());
504
		path.removeLastSegments(1).toFile().mkdirs();
505
		// Do write
506
		FileOutputStream fos = new FileOutputStream(destFile);
507
		OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
508
		writer.write(sb.toString());
509
		writer.close();
510
	}
511
512
	/**
513
	 * Write the content from a InputStream to a file.
514
	 * 
515
	 * @param destPath
516
	 *            - the path of the destination file.
517
	 * @param in
518
	 *            - the ImputSteam whose content will be written to the
519
	 *            destination file.
520
	 * @throws IOException
521
	 */
522
	private void writeFile(IPath destPath, InputStream in) throws IOException {
523
		// Make necessary Dirs
524
		destPath.removeLastSegments(1).toFile().mkdirs();
525
		// Do write
526
		FileOutputStream out = new FileOutputStream(destPath.toFile());
527
		Utils.copyInputToOutput(in, out);
528
	}
529
530
	/**
531
	 * Add the created Midlet declaration to JAD file.
532
	 * 
533
	 * @param javaSourceFile
534
	 *            - the Java source file just generated from a template.
535
	 * @param monitor
536
	 * @throws IOException
537
	 * @throws CoreException
538
	 */
539
	private void addMidletToJAD(File javaSourceFile, IProgressMonitor monitor)
540
			throws IOException, CoreException {
541
		// create ICompilationUnit from File
542
		String path = javaSourceFile.getAbsolutePath();
543
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
544
		IFile javaSrcFile = root.getFileForLocation(new Path(path));
545
		ICompilationUnit cu = (ICompilationUnit) JavaCore.create(javaSrcFile);
546
		if (cu == null) {
547
			return;
548
		}
549
		// find Midlets and add them to JAD
550
		IType[] types = cu.getAllTypes();
551
		for (IType type : types) {
552
			if (Utils.isMidlet(type, monitor)) {
553
				writeMidletDeclarationToJAD(type, monitor);
554
			}
555
		}
556
	}
557
558
	/**
559
	 * Add Midlet declaration to JAD file.
560
	 * 
561
	 * @param midlet
562
	 * @param monitor
563
	 * 
564
	 * @throws IOException
565
	 * @throws CoreException
566
	 */
567
	private void writeMidletDeclarationToJAD(IType midlet,
568
			IProgressMonitor monitor) throws IOException, CoreException {
569
		// Pull out the midlet suite that the type was created in
570
		IJavaProject javaProject = (IJavaProject) midlet
571
				.getAncestor(IJavaElement.JAVA_PROJECT);
572
		IMidletSuiteProject midletSuite = MidletSuiteFactory
573
				.getMidletSuiteProject(javaProject);
574
575
		ApplicationDescriptor desc = midletSuite.getApplicationDescriptor();
576
		if (desc != null) {
577
			ApplicationDescriptor.MidletDefinition def = new ApplicationDescriptor.MidletDefinition(
578
					desc.getMidletCount() + 1, midlet.getElementName(),
579
					template.getMidletIconPath(), midlet
580
							.getFullyQualifiedName());
581
			desc.addMidletDefinition(def);
582
			desc.store();
583
584
			IFile jadFile = midletSuite.getApplicationDescriptorFile();
585
			jadFile.refreshLocal(IResource.DEPTH_ONE, monitor);
586
		}
587
	}
588
589
	/**
590
	 * The Java template file name may need to be substituted.
591
	 * 
592
	 * @param fileName
593
	 * @return
594
	 */
595
	private String substituteJavaTemplateFileName(String fileName) {
596
		StringBuffer sb = getSbAfterSubstituteTemplates(new StringBuffer(
597
				fileName));
598
		return sb.toString();
599
	}
600
601
	/**
602
	 * Substitute all the template options. Before substituting, A StringBuffer
603
	 * may appear as "abc-$toBeSubstituted$-xyz"; after substituting, the
604
	 * StringBuffer will be like this: "abc-substituted-xyz".
605
	 * <p>
606
	 * "$toBeSubstituted$" is the template option, "substituted" is the value of
607
	 * the template option.
608
	 * 
609
	 * @param sb
610
	 * @return
611
	 */
612
	private StringBuffer getSbAfterSubstituteTemplates(StringBuffer sb) {
613
		// Replace template values
614
		int offset = 0;
615
		Matcher matcher = SUBSTITUTION_PATTERN.matcher(sb);
616
617
		while (matcher.find(offset)) {
618
			// The matched string may like this: $toBeSubstituted$
619
			String referencedValue = matcher.group();
620
			// The name of the template option may like this: toBeSubstituted
621
			String optionName = referencedValue.substring(1, referencedValue
622
					.length() - 1);
623
			// The string used to substitute the template option string.
624
			String resolvedValue = template.getSubstituteStringFor(optionName);
625
			// do substitute
626
			sb.replace(matcher.start(), matcher.end(), resolvedValue);
627
			// Figure out the new offset, based on the replaced
628
			// string length
629
			offset = matcher.start() + resolvedValue.length();
630
		}
631
		return sb;
632
	}
633
634
	/**
635
	 * Get a StringBuffer from a InputStream.
636
	 * 
637
	 * @param is
638
	 * @return
639
	 * @throws UnsupportedEncodingException
640
	 * @throws IOException
641
	 */
642
	private StringBuffer getSbBeforeSubstituteTemplates(InputStream is)
643
			throws UnsupportedEncodingException, IOException {
644
		// Read in the template
645
		int charsRead;
646
		char[] buffer = new char[1024];
647
648
		Reader reader = new InputStreamReader(is, "UTF-8");//$NON-NLS-N$
649
		StringBuffer sb = new StringBuffer();
650
		while ((charsRead = reader.read(buffer)) != -1) {
651
			sb.append(buffer, 0, charsRead);
652
		}
653
654
		is.close();
655
		return sb;
656
	}
657
658
	/**
659
	 * Get the URL of the template folder. You should implement this method in
660
	 * your subclass. Typically, your method may appear like this:
661
	 * <p>
662
	 * <code>@Override</code>
663
	 * <p>
664
	 * <code>protected URL getTemplateFolderURL() {</code>
665
	 * <p>
666
	 * <code>   URL templateFolderURL = getClass().getResource(</code>
667
	 * <p>
668
	 * <code>		"/" + MidletTemplate.TEMPLATE_FOLDER + "/helloWorld");</code>
669
	 * <p>
670
	 * <code>return templateFolderURL;</code>
671
	 * <p>
672
	 * <code><p>}</code>
673
	 * <p>
674
	 * 
675
	 * @return - the URL of the folder contains your template.
676
	 */
677
	protected abstract URL getTemplateFolderURL();
678
679
	/**
680
	 * Create and return a subclass of {@link MidletTemplate}. The subclass will
681
	 * be used to substitute template strings in your template.
682
	 * 
683
	 * @return - a MidletTemplate
684
	 */
685
	protected abstract MidletTemplate createTemplate();
686
}
(-)src/org/eclipse/mtj/ui/template/StringOption.java (+70 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.template;
14
15
import org.eclipse.mtj.ui.internal.template.MidletTemplateWizardPage;
16
import org.eclipse.swt.SWT;
17
import org.eclipse.swt.events.ModifyEvent;
18
import org.eclipse.swt.events.ModifyListener;
19
import org.eclipse.swt.layout.GridData;
20
import org.eclipse.swt.widgets.Composite;
21
import org.eclipse.swt.widgets.Text;
22
23
/**
24
 * This class is used to provide a template option that contains a string value.
25
 * When you add a StringOption to your {@link MidletTemplate}, the
26
 * {@link MidletTemplateWizardPage} will appear contains one more string field
27
 * that allow the user to change the default value of this StringOption.
28
 * 
29
 * @author wangf
30
 * 
31
 */
32
public class StringOption extends TemplateOption {
33
	/**
34
	 * @see TemplateOption#TemplateOption(String, String, Object)
35
	 * @param name
36
	 * @param label
37
	 * @param defaultValue
38
	 */
39
	public StringOption(String name, String label, String defaultValue) {
40
		super(name, label, defaultValue);
41
	}
42
43
	/**
44
	 * Create a single line Text control with a label. The control will display
45
	 * on the {@link MidletTemplateWizardPage}. User can change the default
46
	 * option value by set the text of Text control.
47
	 */
48
	@Override
49
	public void createControl(Composite container, int span) {
50
		// Create the label of the Text.
51
		createLabel(container);
52
		// Create the text.
53
		final Text text = new Text(container, SWT.SINGLE | SWT.BORDER);
54
		if (getValue() != null) {
55
			text.setText(getValue().toString());
56
		}
57
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
58
		gd.horizontalSpan = span - 1;
59
		text.setLayoutData(gd);
60
61
		text.addModifyListener(new ModifyListener() {
62
63
			public void modifyText(ModifyEvent e) {
64
				StringOption.this.setValue(text.getText());
65
			}
66
67
		});
68
	}
69
70
}
(-)src/org/eclipse/mtj/ui/template/TemplateOption.java (+129 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.template;
14
15
import org.eclipse.mtj.ui.internal.template.MidletTemplateWizardPage;
16
import org.eclipse.swt.SWT;
17
import org.eclipse.swt.widgets.Composite;
18
import org.eclipse.swt.widgets.Label;
19
20
/**
21
 * This class is a base class of template options.
22
 * 
23
 * @author wangf
24
 * 
25
 */
26
public abstract class TemplateOption {
27
	private String name;
28
	private String label;
29
	private Object value;
30
31
	/**
32
	 * The constructor.
33
	 * 
34
	 * @param name
35
	 *            - the name of the template option. For example, you create a
36
	 *            TemplateOption for a template key string $toBeSubstituted$,
37
	 *            the name of this TemplateOption must be "toBeSubstituted"
38
	 * @param label
39
	 *            - the label of the template option. It will appear as a label
40
	 *            on the UI {@link MidletTemplateWizardPage}.
41
	 * @param value
42
	 *            - the default value of the TemplateOption. By default(if you
43
	 *            don't override
44
	 *            {@link MidletTemplate#getSubstituteStringFor(String optionName)}
45
	 *            method), value.toString() will be used as the substitute
46
	 *            string of this TemplateOption.
47
	 */
48
	public TemplateOption(String name, String label, Object value) {
49
		this.name = name;
50
		this.label = label;
51
		this.value = value;
52
	}
53
54
	/**
55
	 * create a label and set the text to the "label" field variable of this
56
	 * class.
57
	 * 
58
	 * @param parent
59
	 * @return
60
	 */
61
	protected Label createLabel(Composite parent) {
62
		Label label = new Label(parent, SWT.NULL);
63
		label.setText(getLabel());
64
		return label;
65
	}
66
67
	/**
68
	 * Create a control for this template option which will be displayed on
69
	 * {@link MidletTemplateWizardPage}
70
	 * 
71
	 * @param container
72
	 * @param span
73
	 */
74
	public abstract void createControl(Composite container, int span);
75
76
	@Override
77
	public int hashCode() {
78
		final int prime = 31;
79
		int result = 1;
80
		result = prime * result + ((name == null) ? 0 : name.hashCode());
81
		return result;
82
	}
83
84
	/**
85
	 * If the name of two objects equal with each other, we assume the objects
86
	 * equal with each other. Do NOT change the equals behavior in the subclass.
87
	 */
88
	@Override
89
	public boolean equals(Object obj) {
90
		if (this == obj)
91
			return true;
92
		if (obj == null)
93
			return false;
94
		if (getClass() != obj.getClass())
95
			return false;
96
		TemplateOption other = (TemplateOption) obj;
97
		if (name == null) {
98
			if (other.name != null)
99
				return false;
100
		} else if (!name.equals(other.name))
101
			return false;
102
		return true;
103
	}
104
105
	public String getName() {
106
		return name;
107
	}
108
109
	public void setName(String name) {
110
		this.name = name;
111
	}
112
113
	public String getLabel() {
114
		return label;
115
	}
116
117
	public void setLabel(String label) {
118
		this.label = label;
119
	}
120
121
	public Object getValue() {
122
		return value;
123
	}
124
125
	public void setValue(Object value) {
126
		this.value = value;
127
	}
128
129
}
(-)src/org/eclipse/mtj/ui/MtjPerspectiveFactory.java (-81 / +84 lines)
Lines 25-118 Link Here
25
 */
25
 */
26
public class MtjPerspectiveFactory implements IPerspectiveFactory {
26
public class MtjPerspectiveFactory implements IPerspectiveFactory {
27
27
28
    private IPageLayout layout;
28
	private IPageLayout layout;
29
29
30
    /*
30
	/*
31
     * (non-Javadoc)
31
	 * (non-Javadoc)
32
     * 
32
	 * 
33
     * @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
33
	 * @see
34
     */
34
	 * org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui
35
    public void createInitialLayout(IPageLayout layout) {
35
	 * .IPageLayout)
36
        this.layout = layout;
36
	 */
37
        addViews();
37
	public void createInitialLayout(IPageLayout layout) {
38
        addActionSets();
38
		this.layout = layout;
39
        addNewWizardShortcuts();
39
		addViews();
40
        addPerspectiveShortcuts();
40
		addActionSets();
41
        addViewShortcuts();
41
		addNewWizardShortcuts();
42
    }
42
		addPerspectiveShortcuts();
43
		addViewShortcuts();
44
	}
43
45
44
    private void addPerspectiveShortcuts() {
46
	private void addPerspectiveShortcuts() {
45
        layout.addPerspectiveShortcut(JavaUI.ID_PERSPECTIVE);
47
		layout.addPerspectiveShortcut(JavaUI.ID_PERSPECTIVE);
46
        layout.addPerspectiveShortcut(IDebugUIConstants.ID_DEBUG_PERSPECTIVE);
48
		layout.addPerspectiveShortcut(IDebugUIConstants.ID_DEBUG_PERSPECTIVE);
47
    }
49
	}
48
50
49
    private void addViews() {
51
	private void addViews() {
50
        // Add Package Explorer, Navigator and Hierarchy views to left
52
		// Add Package Explorer, Navigator and Hierarchy views to left
51
        IFolderLayout topLeft = layout.createFolder("topLeft", //$NON-NLS-1$
53
		IFolderLayout topLeft = layout.createFolder("topLeft", //$NON-NLS-1$
52
                IPageLayout.LEFT, 0.25f, layout.getEditorArea());
54
				IPageLayout.LEFT, 0.25f, layout.getEditorArea());
53
        topLeft.addView(JavaUI.ID_PACKAGES);
55
		topLeft.addView(JavaUI.ID_PACKAGES);
54
        topLeft.addView(IPageLayout.ID_RES_NAV);
56
		topLeft.addView(IPageLayout.ID_RES_NAV);
55
        topLeft.addView(JavaUI.ID_TYPE_HIERARCHY);
57
		topLeft.addView(JavaUI.ID_TYPE_HIERARCHY);
56
        // Add Problems, Javadoc and Tasks views to bottom
58
		// Add Problems, Javadoc and Tasks views to bottom
57
        IFolderLayout bottom = layout.createFolder("bottomRight", //$NON-NLS-1$
59
		IFolderLayout bottom = layout.createFolder("bottomRight", //$NON-NLS-1$
58
                IPageLayout.BOTTOM, 0.75f, layout.getEditorArea());
60
				IPageLayout.BOTTOM, 0.75f, layout.getEditorArea());
59
        bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
61
		bottom.addView(IPageLayout.ID_PROBLEM_VIEW);
60
        bottom.addView(JavaUI.ID_JAVADOC_VIEW);
62
		bottom.addView(JavaUI.ID_JAVADOC_VIEW);
61
        bottom.addView(IPageLayout.ID_TASK_LIST);
63
		bottom.addView(IPageLayout.ID_TASK_LIST);
62
        // Add Outline view to right
64
		// Add Outline view to right
63
        layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, 0.75f, layout
65
		layout.addView(IPageLayout.ID_OUTLINE, IPageLayout.RIGHT, 0.75f, layout
64
                .getEditorArea());
66
				.getEditorArea());
65
    }
67
	}
66
68
67
    private void addActionSets() {
69
	private void addActionSets() {
68
        layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
70
		layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
69
        layout.addActionSet(JavaUI.ID_ACTION_SET);
71
		layout.addActionSet(JavaUI.ID_ACTION_SET);
70
        layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
72
		layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
71
        layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
73
		layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
72
    }
74
	}
73
75
74
    private void addNewWizardShortcuts() {
76
	private void addNewWizardShortcuts() {
75
        layout
77
		layout
76
                .addNewWizardShortcut("org.eclipse.mtj.ui.wizards.NewJ2MEProjectWizard"); //$NON-NLS-1$
78
				.addNewWizardShortcut("org.eclipse.mtj.ui.wizards.NewJ2MEProjectWizard"); //$NON-NLS-1$
77
        layout
79
		layout
78
                .addNewWizardShortcut("org.eclipse.mtj.ui.wizards.NewMidletWizard"); //$NON-NLS-1$
80
				.addNewWizardShortcut("org.eclipse.mtj.ui.wizards.NewMidletWizard"); //$NON-NLS-1$
81
		layout
82
				.addNewWizardShortcut("org.eclipse.mtj.ui.wizards.NewMidletFromTemplateWizard"); //$NON-NLS-1$
83
		layout
84
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
85
		layout
86
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
87
		layout
88
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
89
		layout
90
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$
91
		layout
92
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$
93
		layout
94
				.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewJavaWorkingSetWizard"); //$NON-NLS-1$
95
		layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
96
		layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
97
		layout
98
				.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
99
	}
79
100
80
        layout
101
	private void addViewShortcuts() {
81
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
102
		// views - error log
82
        layout
103
		layout.addShowViewShortcut("org.eclipse.pde.runtime.LogView"); //$NON-NLS-1$
83
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
84
        layout
85
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
86
        layout
87
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$
88
        layout
89
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$
90
        layout
91
                .addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewJavaWorkingSetWizard"); //$NON-NLS-1$
92
        layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
93
        layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
94
        layout
95
                .addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$
96
    }
97
104
98
    private void addViewShortcuts() {
105
		// views - java
99
        // views - error log
106
		layout.addShowViewShortcut(JavaUI.ID_PACKAGES);
100
        layout.addShowViewShortcut("org.eclipse.pde.runtime.LogView"); //$NON-NLS-1$
107
		layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
108
		layout.addShowViewShortcut(JavaUI.ID_SOURCE_VIEW);
109
		layout.addShowViewShortcut(JavaUI.ID_JAVADOC_VIEW);
101
110
102
        // views - java
111
		// views - debugging
103
        layout.addShowViewShortcut(JavaUI.ID_PACKAGES);
112
		layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
104
        layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
105
        layout.addShowViewShortcut(JavaUI.ID_SOURCE_VIEW);
106
        layout.addShowViewShortcut(JavaUI.ID_JAVADOC_VIEW);
107
113
108
        // views - debugging
114
		// views - standard workbench
109
        layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW);
115
		layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
110
116
		layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
111
        // views - standard workbench
117
		layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
112
        layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
118
		layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
113
        layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
119
		layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
114
        layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
120
	}
115
        layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
116
        layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID);
117
    }
118
}
121
}
(-)src/org/eclipse/mtj/ui/internal/wizards/importer/eclipseme/StatusUtil.java (-65 lines)
Lines 1-65 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from 
21
 *     		org.eclipse.ui.internal.wizards.datatransfer.DataTransferMessages,
22
 *     		which located in org.eclipse.ui.ide plug-in. Remove unused methods.
23
 *******************************************************************************/
24
package org.eclipse.mtj.ui.internal.wizards.importer.eclipseme;
25
26
import org.eclipse.core.runtime.IStatus;
27
import org.eclipse.core.runtime.Status;
28
import org.eclipse.mtj.ui.IMTJUIConstants;
29
30
/**
31
 * Utility class to create status objects.
32
 * 
33
 * PRIVATE This class is an internal implementation class and should not be
34
 * referenced or sub-classed outside of the workbench
35
 * 
36
 */
37
public class StatusUtil {
38
	/**
39
	 * This method must not be called outside the workbench.
40
	 * 
41
	 * Utility method for creating status.
42
	 * 
43
	 * @param severity
44
	 * @param message
45
	 * @param exception
46
	 * @return {@link IStatus}
47
	 */
48
	public static IStatus newStatus(int severity, String message,
49
			Throwable exception) {
50
51
		String statusMessage = message;
52
		if (message == null || message.trim().length() == 0) {
53
			if (exception == null) {
54
				throw new IllegalArgumentException();
55
			} else if (exception.getMessage() == null) {
56
				statusMessage = exception.toString();
57
			} else {
58
				statusMessage = exception.getMessage();
59
			}
60
		}
61
62
		return new Status(severity, IMTJUIConstants.PLUGIN_ID, severity,
63
				statusMessage, exception);
64
	}
65
}
(-)src/org/eclipse/mtj/ui/internal/wizards/importer/eclipseme/ImportEclipseMEProjectWizardPage.java (+1 lines)
Lines 92-97 Link Here
92
import org.eclipse.mtj.core.model.project.MidletSuiteFactory;
92
import org.eclipse.mtj.core.model.project.MidletSuiteFactory;
93
import org.eclipse.mtj.core.model.project.impl.MidletSuiteProject;
93
import org.eclipse.mtj.core.model.project.impl.MidletSuiteProject;
94
import org.eclipse.mtj.ui.IMTJUIConstants;
94
import org.eclipse.mtj.ui.IMTJUIConstants;
95
import org.eclipse.mtj.ui.internal.wizards.StatusUtil;
95
import org.eclipse.osgi.util.NLS;
96
import org.eclipse.osgi.util.NLS;
96
import org.eclipse.swt.SWT;
97
import org.eclipse.swt.SWT;
97
import org.eclipse.swt.events.FocusAdapter;
98
import org.eclipse.swt.events.FocusAdapter;
(-)src/org/eclipse/mtj/ui/internal/wizards/StatusUtil.java (+169 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from 
21
 *     		org.eclipse.jdt.internal.ui.dialogs.StatusUtil and modified.
22
 *******************************************************************************/
23
package org.eclipse.mtj.ui.internal.wizards;
24
25
import org.eclipse.core.runtime.IStatus;
26
import org.eclipse.core.runtime.Status;
27
28
import org.eclipse.jface.dialogs.DialogPage;
29
import org.eclipse.jface.dialogs.IMessageProvider;
30
import org.eclipse.mtj.ui.IMTJUIConstants;
31
32
/**
33
 * A utility class to work with IStatus.
34
 */
35
public class StatusUtil {
36
	/**
37
	 * This method must not be called outside MTJ.
38
	 * 
39
	 * Utility method for creating status.
40
	 * 
41
	 * @param severity
42
	 * @param message
43
	 * @param exception
44
	 * @return {@link IStatus}
45
	 */
46
	public static IStatus newStatus(int severity, String message,
47
			Throwable exception) {
48
49
		String statusMessage = message;
50
		if (message == null || message.trim().length() == 0) {
51
			if (exception == null) {
52
				throw new IllegalArgumentException();
53
			} else if (exception.getMessage() == null) {
54
				statusMessage = exception.toString();
55
			} else {
56
				statusMessage = exception.getMessage();
57
			}
58
		}
59
60
		return new Status(severity, IMTJUIConstants.PLUGIN_ID, severity,
61
				statusMessage, exception);
62
	}
63
64
	/**
65
	 * This method must not be called outside MTJ.
66
	 * 
67
	 * Utility method for creating status.
68
	 * 
69
	 * @param severity
70
	 * @param message
71
	 * @return {@link IStatus}
72
	 */
73
	public static IStatus newStatus(int severity, String message) {
74
		return new Status(severity, IMTJUIConstants.PLUGIN_ID, message);
75
	}
76
77
	/**
78
	 * Compares two instances of <code>IStatus</code>. The more severe is
79
	 * returned: An error is more severe than a warning, and a warning is more
80
	 * severe than OK. If the two status have the same severity, the second is
81
	 * returned.
82
	 * 
83
	 * @param s1
84
	 *            first status
85
	 * @param s2
86
	 *            second status
87
	 * @return the more severe status
88
	 */
89
	public static IStatus getMoreSevere(IStatus s1, IStatus s2) {
90
		if (s1.getSeverity() > s2.getSeverity()) {
91
			return s1;
92
		} else {
93
			return s2;
94
		}
95
	}
96
97
	/**
98
	 * Finds the most severe status from a array of status. An error is more
99
	 * severe than a warning, and a warning is more severe than OK.
100
	 * 
101
	 * @param statuses
102
	 *            an array of status
103
	 * @return the most severe status
104
	 */
105
	public static IStatus getMostSevere(IStatus[] statuses) {
106
		IStatus max = null;
107
		for (int i = 0; i < statuses.length; i++) {
108
			IStatus curr = statuses[i];
109
			if (curr.matches(IStatus.ERROR)) {
110
				return curr;
111
			}
112
			if (max == null || curr.getSeverity() > max.getSeverity()) {
113
				max = curr;
114
			}
115
		}
116
		return max;
117
	}
118
119
	/**
120
	 * Decide if all the status are acceptable. If one of the status's severity
121
	 * is greater than IStatus.WARNING, it will return false.
122
	 * 
123
	 * @param statuses
124
	 *            - A array of status to be decided if all of them are
125
	 *            acceptable.
126
	 * @return - If all the statuses are acceptable.
127
	 */
128
	public static boolean allAreAcceptable(IStatus[] statuses) {
129
		IStatus mostSevere = getMostSevere(statuses);
130
		if (mostSevere.getSeverity() <= IStatus.WARNING) {
131
			return true;
132
		} else {
133
			return false;
134
		}
135
	}
136
137
	/**
138
	 * Applies the status to the status line of a dialog page.
139
	 * 
140
	 * @param page
141
	 *            the dialog page
142
	 * @param status
143
	 *            the status to apply
144
	 */
145
	public static void applyToStatusLine(DialogPage page, IStatus status) {
146
		String message = status.getMessage();
147
		if (message != null && message.length() == 0) {
148
			message = null;
149
		}
150
		switch (status.getSeverity()) {
151
		case IStatus.OK:
152
			page.setMessage(message, IMessageProvider.NONE);
153
			page.setErrorMessage(null);
154
			break;
155
		case IStatus.WARNING:
156
			page.setMessage(message, IMessageProvider.WARNING);
157
			page.setErrorMessage(null);
158
			break;
159
		case IStatus.INFO:
160
			page.setMessage(message, IMessageProvider.INFORMATION);
161
			page.setErrorMessage(null);
162
			break;
163
		default:
164
			page.setMessage(null);
165
			page.setErrorMessage(message);
166
			break;
167
		}
168
	}
169
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/MidletTemplatesSelectionPage.java (+619 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
package org.eclipse.mtj.ui.internal.wizards.template;
13
14
import java.util.List;
15
16
import org.eclipse.core.resources.IProject;
17
import org.eclipse.core.resources.IResource;
18
import org.eclipse.core.resources.ResourcesPlugin;
19
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.IAdaptable;
21
import org.eclipse.core.runtime.IPath;
22
import org.eclipse.core.runtime.IStatus;
23
import org.eclipse.core.runtime.Path;
24
import org.eclipse.jdt.core.IJavaElement;
25
import org.eclipse.jdt.core.IJavaModel;
26
import org.eclipse.jdt.core.IJavaProject;
27
import org.eclipse.jdt.core.IPackageFragmentRoot;
28
import org.eclipse.jdt.core.JavaCore;
29
import org.eclipse.jdt.core.JavaModelException;
30
import org.eclipse.jdt.ui.JavaElementComparator;
31
import org.eclipse.jdt.ui.JavaElementLabelProvider;
32
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
33
import org.eclipse.jface.dialogs.Dialog;
34
import org.eclipse.jface.resource.ImageDescriptor;
35
import org.eclipse.jface.viewers.ILabelProvider;
36
import org.eclipse.jface.viewers.ISelectionChangedListener;
37
import org.eclipse.jface.viewers.IStructuredContentProvider;
38
import org.eclipse.jface.viewers.IStructuredSelection;
39
import org.eclipse.jface.viewers.LabelProvider;
40
import org.eclipse.jface.viewers.SelectionChangedEvent;
41
import org.eclipse.jface.viewers.TableViewer;
42
import org.eclipse.jface.viewers.Viewer;
43
import org.eclipse.jface.viewers.ViewerFilter;
44
import org.eclipse.jface.window.Window;
45
import org.eclipse.jface.wizard.IWizardNode;
46
import org.eclipse.jface.wizard.Wizard;
47
import org.eclipse.jface.wizard.WizardSelectionPage;
48
import org.eclipse.mtj.core.IMTJCoreConstants;
49
import org.eclipse.mtj.core.internal.MTJCorePlugin;
50
import org.eclipse.mtj.ui.internal.template.TemplateWizardProxy;
51
import org.eclipse.mtj.ui.internal.template.TemplateWizardRegistry;
52
import org.eclipse.mtj.ui.internal.template.WizardNode;
53
import org.eclipse.mtj.ui.internal.wizards.StatusUtil;
54
import org.eclipse.mtj.ui.template.MidletTemplateWizard;
55
import org.eclipse.osgi.util.NLS;
56
import org.eclipse.swt.SWT;
57
import org.eclipse.swt.custom.SashForm;
58
import org.eclipse.swt.events.ModifyEvent;
59
import org.eclipse.swt.events.ModifyListener;
60
import org.eclipse.swt.events.SelectionEvent;
61
import org.eclipse.swt.events.SelectionListener;
62
import org.eclipse.swt.graphics.Image;
63
import org.eclipse.swt.layout.GridData;
64
import org.eclipse.swt.layout.GridLayout;
65
import org.eclipse.swt.widgets.Button;
66
import org.eclipse.swt.widgets.Composite;
67
import org.eclipse.swt.widgets.Label;
68
import org.eclipse.swt.widgets.Text;
69
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
70
71
/**
72
 * We use this wizard page for the user to select a Midlet template
73
 * 
74
 * @author wangf
75
 * 
76
 */
77
public class MidletTemplatesSelectionPage extends WizardSelectionPage implements
78
		ISelectionChangedListener {
79
80
	private TableViewer templateSelectionViewer;
81
	private Text description;
82
	/**
83
	 * The Java source folder of the MTJ Midlet Suite project.
84
	 */
85
	private IPackageFragmentRoot currentJavaRoot;
86
	/**
87
	 * The resource folder of the MTJ Midlet Suite project.
88
	 */
89
	private IPackageFragmentRoot currentResourceRoot;
90
	private Text javaSourceFolderText;
91
	private Text resourceFolderText;
92
	private IStatus javaSourceFolderStatus = getErrorStatus("");
93
	private IStatus resourceFolderStatus = getErrorStatus("");
94
95
	public MidletTemplatesSelectionPage(String pageName) {
96
		super(pageName);
97
		setTitle(TemplateWizardMessages.WizardTemplateSelectionPage_title);
98
		setDescription(TemplateWizardMessages.WizardTemplateSelectionPage_desc);
99
	}
100
101
	// ----------------------- begin initialize---------------------------
102
	/**
103
	 * Initialize Java Source Folder and Resource Folder. Since we have no way
104
	 * to know which source folder is Java Source Folder and which source folder
105
	 * is Resource Folder, we just take the first source folder as Java Source
106
	 * folder and take the second folder as the Resource Folder. If there is
107
	 * only one source folder of the MTJ Midlet Suite project, we set Java
108
	 * Source Folder and Resource Folder the same one.
109
	 */
110
	private void initSourceFolders() {
111
		IJavaElement initialJavaElement = getInitialJavaElement();
112
		if (initialJavaElement == null) {
113
			return;
114
		}
115
		try {
116
			IJavaProject jproject = initialJavaElement.getJavaProject();
117
			if (jproject != null) {
118
				if (jproject.exists()) {
119
					IPackageFragmentRoot[] sourceRoots = new IPackageFragmentRoot[2];
120
					int sourceRootsAmount = 0;
121
					IPackageFragmentRoot[] roots = jproject
122
							.getPackageFragmentRoots();
123
					// Try to get two source folders
124
					for (int i = 0; i < roots.length; i++) {
125
						if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
126
							sourceRoots[sourceRootsAmount] = roots[i];
127
							sourceRootsAmount++;
128
							if (sourceRootsAmount == 2) {
129
								break;
130
							}
131
						}
132
					}
133
					// Initialize Java Source Folder and Resource Folder
134
					if (sourceRootsAmount == 2) {
135
						// two source folders
136
						currentJavaRoot = sourceRoots[0];
137
						currentResourceRoot = sourceRoots[1];
138
					} else if (sourceRootsAmount == 1) {
139
						// one source folder
140
						currentJavaRoot = sourceRoots[0];
141
						currentResourceRoot = sourceRoots[0];
142
					} else if (sourceRootsAmount == 0) {
143
						// project root as source folder
144
						sourceRoots[0] = jproject
145
								.getPackageFragmentRoot(jproject.getResource());
146
						currentJavaRoot = sourceRoots[0];
147
						currentResourceRoot = sourceRoots[0];
148
					}
149
				}
150
151
			}
152
		} catch (JavaModelException e) {
153
			MTJCorePlugin.log(IStatus.ERROR, e);
154
		}
155
		// initialize the UI
156
		javaSourceFolderText.setText(getSourceFolderName(currentJavaRoot));
157
		resourceFolderText.setText(getSourceFolderName(currentResourceRoot));
158
	}
159
160
	/**
161
	 * Get the initial Java Element. It is the Java element that user selected
162
	 * from the Package Explorer or Navigator.
163
	 * 
164
	 * @return
165
	 */
166
	private IJavaElement getInitialJavaElement() {
167
		IJavaElement javaElement = null;
168
		NewMidletFromTemplateWizard wizard = (NewMidletFromTemplateWizard) MidletTemplatesSelectionPage.this
169
				.getWizard();
170
		javaElement = getJavaElementFromSelection(wizard.getSelection());
171
		return javaElement;
172
	}
173
174
	/**
175
	 * Get Java element from selection.
176
	 * 
177
	 * @param selection
178
	 * @return
179
	 */
180
	protected IJavaElement getJavaElementFromSelection(
181
			IStructuredSelection selection) {
182
		IJavaElement jelem = null;
183
		if (selection != null && !selection.isEmpty()) {
184
			Object selectedElement = selection.getFirstElement();
185
			if (selectedElement instanceof IAdaptable) {
186
				IAdaptable adaptable = (IAdaptable) selectedElement;
187
188
				jelem = (IJavaElement) adaptable.getAdapter(IJavaElement.class);
189
				if (jelem == null) {
190
					IResource resource = (IResource) adaptable
191
							.getAdapter(IResource.class);
192
					if (resource != null
193
							&& resource.getType() != IResource.ROOT) {
194
						while (jelem == null
195
								&& resource.getType() != IResource.PROJECT) {
196
							resource = resource.getParent();
197
							jelem = (IJavaElement) resource
198
									.getAdapter(IJavaElement.class);
199
						}
200
						if (jelem == null) {
201
							jelem = JavaCore.create(resource); // java project
202
						}
203
					}
204
				}
205
			}
206
		}
207
208
		return jelem;
209
	}
210
211
	/**
212
	 * Get the name of source folder.
213
	 * 
214
	 * @param root -
215
	 *            Java source folder or resource folder of MTJ Midlet Suite
216
	 *            project.
217
	 * @return
218
	 */
219
	private String getSourceFolderName(IPackageFragmentRoot root) {
220
		// IPackageFragmentRoot root = getSourceFolder();
221
		String folderName = (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$
222
		return folderName;
223
	}
224
225
	// ----------------------- end initialize---------------------------
226
227
	// ----------------------- begin UI creation---------------------------
228
	public void createControl(Composite parent) {
229
		// The container
230
		Composite container = new Composite(parent, SWT.NONE);
231
		GridLayout layout = new GridLayout();
232
		layout.verticalSpacing = 10;
233
		container.setLayout(layout);
234
		container.setLayoutData(new GridData(GridData.FILL_BOTH));
235
		// Create the source folder choosing section
236
		createSourceFolderSection(container);
237
		// The "Available Templates" label
238
		Label templatesLabel = new Label(container, SWT.NONE);
239
		templatesLabel
240
				.setText(TemplateWizardMessages.WizardTemplateSelectionPage_templates);
241
		// the SashForm contains Templates TableViewer and Description Text
242
		SashForm sashForm = new SashForm(container, SWT.HORIZONTAL);
243
		GridData gd = new GridData(GridData.FILL_BOTH);
244
		gd.widthHint = 300;
245
		sashForm.setLayoutData(gd);
246
		// Create template TableViewer
247
		createTemplateViewer(sashForm);
248
		// Description of the template
249
		description = new Text(sashForm, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY
250
				| SWT.BORDER);
251
252
		Dialog.applyDialogFont(container);
253
		setControl(container);
254
	}
255
256
	/**
257
	 * Create the source folder choosing section
258
	 * 
259
	 * @param parent
260
	 */
261
	private void createSourceFolderSection(Composite parent) {
262
		Composite container = new Composite(parent, SWT.NONE);
263
		GridLayout layout = new GridLayout(3, false);
264
		container.setLayout(layout);
265
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
266
		container.setLayoutData(gd);
267
268
		Label sourceFolderLabel = new Label(container, SWT.NONE);
269
		sourceFolderLabel
270
				.setText(TemplateWizardMessages.WizardTemplateSelectionPage_JavaRoot);
271
		gd = new GridData();
272
		sourceFolderLabel.setLayoutData(gd);
273
274
		javaSourceFolderText = new Text(container, SWT.SINGLE | SWT.BORDER);
275
		gd = new GridData(GridData.FILL_HORIZONTAL);
276
		javaSourceFolderText.setLayoutData(gd);
277
		javaSourceFolderText.addModifyListener(new ModifyListener() {
278
279
			public void modifyText(ModifyEvent e) {
280
				javaSourceFolderStatus = validateProjectNatureAndSourceFolder(javaSourceFolderText
281
						.getText());
282
				// validation
283
				validateAndDisPlayStatus();
284
			}
285
286
		});
287
288
		Button javaSrcFolderBrowseButton = new Button(container, SWT.PUSH);
289
		javaSrcFolderBrowseButton
290
				.setText(TemplateWizardMessages.WizardTemplateSelectionPage_SourceFolderBrowse);
291
		javaSrcFolderBrowseButton.addSelectionListener(new SelectionListener() {
292
			public void widgetSelected(SelectionEvent e) {
293
				chooseJavaSourceFolder();
294
			}
295
296
			public void widgetDefaultSelected(SelectionEvent e) {
297
				chooseJavaSourceFolder();
298
			}
299
		});
300
301
		Label resourceFolderLabel = new Label(container, SWT.NONE);
302
		resourceFolderLabel
303
				.setText(TemplateWizardMessages.WizardTemplateSelectionPage_ResourceRoot);
304
		gd = new GridData();
305
		resourceFolderLabel.setLayoutData(gd);
306
307
		resourceFolderText = new Text(container, SWT.SINGLE | SWT.BORDER);
308
		gd = new GridData(GridData.FILL_HORIZONTAL);
309
		resourceFolderText.setLayoutData(gd);
310
		resourceFolderText.addModifyListener(new ModifyListener() {
311
312
			public void modifyText(ModifyEvent e) {
313
				resourceFolderStatus = validateProjectNatureAndSourceFolder(resourceFolderText
314
						.getText());
315
				// validation
316
				validateAndDisPlayStatus();
317
			}
318
319
		});
320
321
		Button rsourceFolderBrowseButton = new Button(container, SWT.PUSH);
322
		rsourceFolderBrowseButton
323
				.setText(TemplateWizardMessages.WizardTemplateSelectionPage_SourceFolderBrowse);
324
		rsourceFolderBrowseButton.addSelectionListener(new SelectionListener() {
325
			public void widgetSelected(SelectionEvent e) {
326
				chooseResourceFolder();
327
			}
328
329
			public void widgetDefaultSelected(SelectionEvent e) {
330
				chooseResourceFolder();
331
			}
332
		});
333
		// Initialize source folders
334
		initSourceFolders();
335
	}
336
337
	/**
338
	 * Create a table viewer to diaplay all the templates.
339
	 * 
340
	 * @param sashForm
341
	 */
342
	private void createTemplateViewer(SashForm sashForm) {
343
		// Template list
344
		templateSelectionViewer = new TableViewer(sashForm, SWT.BORDER);
345
		templateSelectionViewer
346
				.setContentProvider(new IStructuredContentProvider() {
347
348
					@SuppressWarnings("unchecked")
349
					public Object[] getElements(Object inputElement) {
350
						List<TemplateWizardProxy> templates = (List<TemplateWizardProxy>) inputElement;
351
						return templates
352
								.toArray(new TemplateWizardProxy[templates
353
										.size()]);
354
					}
355
356
					public void dispose() {
357
					}
358
359
					public void inputChanged(Viewer viewer, Object oldInput,
360
							Object newInput) {
361
					}
362
363
				});
364
		templateSelectionViewer.setLabelProvider(new LabelProvider() {
365
			@Override
366
			public Image getImage(Object element) {
367
				TemplateWizardProxy proxy = (TemplateWizardProxy) element;
368
				ImageDescriptor descriptor = proxy.getIcon();
369
				return descriptor == null ? null : descriptor.createImage();
370
			}
371
		});
372
		// Get all the template wizards
373
		List<TemplateWizardProxy> templates = TemplateWizardRegistry
374
				.getTemplateWizardProxies();
375
		// Fill template viewer with template wizards
376
		templateSelectionViewer.setInput(templates);
377
		// Add listener
378
		templateSelectionViewer.addSelectionChangedListener(this);
379
	}
380
381
	// ----------------------- end UI creation---------------------------
382
383
	// ----------------------- begin event handling---------------------------
384
	/**
385
	 * User choose Java Source Folder
386
	 */
387
	private void chooseJavaSourceFolder() {
388
		IPackageFragmentRoot root = chooseContainer(currentJavaRoot);
389
		if (root != null) {
390
			currentJavaRoot = root;
391
			javaSourceFolderText.setText(getSourceFolderName(root));
392
		}
393
	}
394
395
	/**
396
	 * User choose Resource Folder
397
	 */
398
	private void chooseResourceFolder() {
399
		IPackageFragmentRoot root = chooseContainer(currentResourceRoot);
400
		if (root != null) {
401
			currentResourceRoot = root;
402
			resourceFolderText.setText(getSourceFolderName(root));
403
		}
404
	}
405
406
	/**
407
	 * Opens a selection dialog that allows to select a source container.
408
	 * 
409
	 * @return returns the selected package fragment root or <code>null</code>
410
	 *         if the dialog has been canceled. The caller typically sets the
411
	 *         result to the container input field.
412
	 */
413
	private IPackageFragmentRoot chooseContainer(
414
			IPackageFragmentRoot currentSelection) {
415
		Class<?>[] acceptedClasses = new Class[] { IPackageFragmentRoot.class,
416
				IJavaProject.class };
417
		TypedElementSelectionValidator validator = new TypedElementSelectionValidator(
418
				acceptedClasses, false) {
419
			public boolean isSelectedValid(Object element) {
420
				try {
421
					if (element instanceof IJavaProject) {
422
						IJavaProject jproject = (IJavaProject) element;
423
						IPath path = jproject.getProject().getFullPath();
424
						return (jproject.findPackageFragmentRoot(path) != null);
425
					} else if (element instanceof IPackageFragmentRoot) {
426
						return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
427
					}
428
					return true;
429
				} catch (JavaModelException e) {
430
					MTJCorePlugin.log(IStatus.ERROR, e);
431
				}
432
				return false;
433
			}
434
		};
435
436
		acceptedClasses = new Class[] { IJavaModel.class,
437
				IPackageFragmentRoot.class, IJavaProject.class };
438
		ViewerFilter filter = new TypedViewerFilter(acceptedClasses) {
439
			public boolean select(Viewer viewer, Object parent, Object element) {
440
				if (element instanceof IPackageFragmentRoot) {
441
					try {
442
						return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
443
					} catch (JavaModelException e) {
444
						MTJCorePlugin.log(IStatus.ERROR, e);
445
						return false;
446
					}
447
				}
448
				return super.select(viewer, parent, element);
449
			}
450
		};
451
452
		StandardJavaElementContentProvider provider = new StandardJavaElementContentProvider();
453
		ILabelProvider labelProvider = new JavaElementLabelProvider(
454
				JavaElementLabelProvider.SHOW_DEFAULT);
455
		ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
456
				getShell(), labelProvider, provider);
457
		dialog.setValidator(validator);
458
		dialog.setComparator(new JavaElementComparator());
459
		dialog
460
				.setTitle(TemplateWizardMessages.MewMidletFromTemplateWizard_ChooseSourceContainerDialog_title);
461
		dialog
462
				.setMessage(TemplateWizardMessages.MewMidletFromTemplateWizard_ChooseSourceContainerDialog_description);
463
		dialog.addFilter(filter);
464
		dialog.setInput(JavaCore.create(ResourcesPlugin.getWorkspace()
465
				.getRoot()));
466
		dialog.setInitialSelection(currentSelection);
467
		dialog.setHelpAvailable(false);
468
469
		if (dialog.open() == Window.OK) {
470
			Object element = dialog.getFirstResult();
471
			if (element instanceof IJavaProject) {
472
				IJavaProject jproject = (IJavaProject) element;
473
				return jproject.getPackageFragmentRoot(jproject.getProject());
474
			} else if (element instanceof IPackageFragmentRoot) {
475
				return (IPackageFragmentRoot) element;
476
			}
477
			return null;
478
		}
479
		return null;
480
	}
481
482
	public void selectionChanged(SelectionChangedEvent event) {
483
		// create and set WizardNode
484
		IStructuredSelection selection = (IStructuredSelection) event
485
				.getSelection();
486
		TemplateWizardProxy templateWizardProxy = (TemplateWizardProxy) selection
487
				.getFirstElement();
488
		if (templateWizardProxy == null) {
489
			setSelectedNode(null);
490
			return;
491
		}
492
		// set wizard node
493
		IWizardNode wizardNode = createWizardNode(templateWizardProxy);
494
		setSelectedNode(wizardNode);
495
		// Set the description of the selected template
496
		description.setText(templateWizardProxy.getDescription());
497
	}
498
499
	/**
500
	 * Create wizard node from TemplateWizardProxy
501
	 * 
502
	 * @param wizardProxy
503
	 * @return
504
	 */
505
	protected IWizardNode createWizardNode(final TemplateWizardProxy wizardProxy) {
506
		return new WizardNode() {
507
508
			@Override
509
			protected Wizard createWizard() throws CoreException {
510
				MidletTemplateWizard midletTemplateWizard = wizardProxy
511
						.createWizard(currentJavaRoot, currentResourceRoot);
512
				return midletTemplateWizard;
513
			}
514
515
		};
516
	}
517
518
	// ----------------------- end event handling---------------------------
519
520
	// ------begin validation --------
521
	/*
522
	 * Do validation once the page is visible.
523
	 */
524
	@Override
525
	public void setVisible(boolean visible) {
526
		super.setVisible(visible);
527
		validateAndDisPlayStatus();
528
	}
529
530
	@Override
531
	public boolean canFlipToNextPage() {
532
		return super.canFlipToNextPage() && isPageComplete();
533
	}
534
535
	/**
536
	 * Validate if the Source Folder is valid
537
	 * 
538
	 * @param sourceFolderPath
539
	 * @return
540
	 */
541
	private IStatus validateProjectNatureAndSourceFolder(String sourceFolderPath) {
542
		IPath path = new Path(sourceFolderPath);
543
		IResource resource = ResourcesPlugin.getWorkspace().getRoot()
544
				.findMember(path);
545
546
		if (resource == null) {
547
			return getErrorStatus(sourceFolderPath);
548
		}
549
550
		IProject project = resource.getProject();
551
		IJavaElement javaElement = JavaCore.create(resource);
552
553
		try {
554
			// validate project nature
555
			if (!project.hasNature(IMTJCoreConstants.J2ME_NATURE_ID)) {
556
				return StatusUtil.newStatus(IStatus.ERROR, NLS.bind(
557
						TemplateWizardMessages.Validation_NotMTJProject,
558
						project.getName()));
559
			}
560
			// validate source folder
561
			if (javaElement instanceof IPackageFragmentRoot) {
562
				IPackageFragmentRoot root = (IPackageFragmentRoot) javaElement;
563
				if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
564
					return getOKStatus();
565
				} else {
566
					return getErrorStatus(sourceFolderPath);
567
				}
568
			} else if (javaElement instanceof IJavaProject) {
569
				IJavaProject jproject = (IJavaProject) javaElement;
570
				IPath projPath = jproject.getProject().getFullPath();
571
				if (jproject.findPackageFragmentRoot(projPath) != null) {
572
					return getOKStatus();
573
				} else {
574
					return getErrorStatus(sourceFolderPath);
575
				}
576
			} else {
577
				return getErrorStatus(sourceFolderPath);
578
			}
579
		} catch (Exception e) {
580
			MTJCorePlugin.log(IStatus.WARNING, e);
581
			return getOKStatus();
582
		}
583
	}
584
585
	/**
586
	 * Return a error status.
587
	 * 
588
	 * @param sourceFolderPath
589
	 * @return
590
	 */
591
	private IStatus getErrorStatus(String sourceFolderPath) {
592
		return StatusUtil.newStatus(IStatus.ERROR, NLS.bind(
593
				TemplateWizardMessages.Validation_NotSourceFolder,
594
				sourceFolderPath));
595
	}
596
597
	/**
598
	 * Return a OK status.
599
	 * 
600
	 * @return
601
	 */
602
	private IStatus getOKStatus() {
603
		return StatusUtil.newStatus(IStatus.OK,
604
				TemplateWizardMessages.WizardTemplateSelectionPage_desc);
605
	}
606
607
	/**
608
	 * Decide if the page is complete and display the validation result message.
609
	 */
610
	private void validateAndDisPlayStatus() {
611
		IStatus[] statuses = { javaSourceFolderStatus, resourceFolderStatus };
612
		IStatus currentStatus = StatusUtil.getMostSevere(statuses);
613
		// Set if the page is complete
614
		setPageComplete(StatusUtil.allAreAcceptable(statuses));
615
		// display status on page
616
		StatusUtil.applyToStatusLine(this, currentStatus);
617
	}
618
	// ------end validation --------
619
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/NewMidletFromTemplateWizard.java (+67 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.wizards.template;
14
15
import org.eclipse.jface.viewers.IStructuredSelection;
16
import org.eclipse.jface.wizard.Wizard;
17
import org.eclipse.ui.INewWizard;
18
import org.eclipse.ui.IWorkbench;
19
20
/**
21
 * Wizard for creating Midlet form template
22
 * 
23
 * @author wangf
24
 * 
25
 */
26
public class NewMidletFromTemplateWizard extends Wizard implements INewWizard {
27
	/**
28
	 * We will use the selection to retrieve source folders.
29
	 */
30
	private IStructuredSelection selection;
31
	private MidletTemplatesSelectionPage templateListSelectionPage;
32
33
	public NewMidletFromTemplateWizard() {
34
		setWindowTitle(TemplateWizardMessages.MewMidletFromTemplateWizard_windowTitle);
35
		setNeedsProgressMonitor(true);
36
		setForcePreviousAndNextButtons(true);
37
	}
38
39
	public void addPages() {
40
		templateListSelectionPage = new MidletTemplatesSelectionPage(
41
				"templateListSelectionPage");
42
		addPage(templateListSelectionPage);
43
44
	}
45
46
	/**
47
	 * This wizard is a wizards selection wizard, so it should always return
48
	 * false.
49
	 */
50
	@Override
51
	public boolean canFinish() {
52
		return false;
53
	}
54
55
	@Override
56
	public boolean performFinish() {
57
		return false;
58
	}
59
60
	public void init(IWorkbench workbench, IStructuredSelection selection) {
61
		this.selection = selection;
62
	}
63
64
	public IStructuredSelection getSelection() {
65
		return selection;
66
	}
67
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/TemplateWizardMessages.java (+50 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.wizards.template;
14
15
import org.eclipse.osgi.util.NLS;
16
17
public class TemplateWizardMessages extends NLS {
18
	private static final String BUNDLE_NAME = "org.eclipse.mtj.ui.internal.wizards.template.messages";//$NON-NLS-N$
19
20
	public static String WizardTemplateSelectionPage_title;
21
	public static String WizardTemplateSelectionPage_desc;
22
23
	public static String WizardTemplateSelectionPage_templates;
24
25
	public static String MewMidletFromTemplateWizard_windowTitle;
26
27
	public static String MewMidletFromTemplateWizard_error_title;
28
29
	public static String MewMidletFromTemplateWizard_error_nothingSelected;
30
31
	public static String MewMidletFromTemplateWizard_ChooseSourceContainerDialog_title;
32
33
	public static String MewMidletFromTemplateWizard_ChooseSourceContainerDialog_description;
34
35
	public static String Validation_NotSourceFolder;
36
37
	public static String ErrorDialogTitle_duringCopy;
38
39
	public static String WizardTemplateSelectionPage_JavaRoot;
40
41
	public static String WizardTemplateSelectionPage_SourceFolderBrowse;
42
43
	public static String WizardTemplateSelectionPage_ResourceRoot;
44
45
	public static String Validation_NotMTJProject;
46
47
	static {
48
		NLS.initializeMessages(BUNDLE_NAME, TemplateWizardMessages.class);
49
	}
50
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/TypedElementSelectionValidator.java (+128 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from {@link org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator}
21
 *******************************************************************************/
22
23
package org.eclipse.mtj.ui.internal.wizards.template;
24
25
import java.util.Collection;
26
27
import org.eclipse.core.runtime.Assert;
28
import org.eclipse.core.runtime.IStatus;
29
import org.eclipse.core.runtime.Status;
30
import org.eclipse.mtj.ui.IMTJUIConstants;
31
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
32
33
/**
34
 * Implementation of a <code>ISelectionValidator</code> to validate the type of
35
 * an element. Empty selections are not accepted.
36
 */
37
public class TypedElementSelectionValidator implements
38
		ISelectionStatusValidator {
39
40
	private IStatus fgErrorStatus = new Status(IStatus.ERROR,
41
			IMTJUIConstants.PLUGIN_ID, ""); //$NON-NLS-1$
42
	private IStatus fgOKStatus = new Status(IStatus.OK,
43
			IMTJUIConstants.PLUGIN_ID, "");//$NON-NLS-1$
44
45
	private Class<?>[] fAcceptedTypes;
46
	private boolean fAllowMultipleSelection;
47
	private Collection<?> fRejectedElements;
48
49
	/**
50
	 * @param acceptedTypes
51
	 *            The types accepted by the validator
52
	 * @param allowMultipleSelection
53
	 *            If set to <code>true</code>, the validator allows multiple
54
	 *            selection.
55
	 */
56
	public TypedElementSelectionValidator(Class<?>[] acceptedTypes,
57
			boolean allowMultipleSelection) {
58
		this(acceptedTypes, allowMultipleSelection, null);
59
	}
60
61
	/**
62
	 * @param acceptedTypes
63
	 *            The types accepted by the validator
64
	 * @param allowMultipleSelection
65
	 *            If set to <code>true</code>, the validator allows multiple
66
	 *            selection.
67
	 * @param rejectedElements
68
	 *            A list of elements that are not accepted
69
	 */
70
	public TypedElementSelectionValidator(Class<?>[] acceptedTypes,
71
			boolean allowMultipleSelection, Collection<?> rejectedElements) {
72
		Assert.isNotNull(acceptedTypes);
73
		fAcceptedTypes = acceptedTypes;
74
		fAllowMultipleSelection = allowMultipleSelection;
75
		fRejectedElements = rejectedElements;
76
	}
77
78
	/*
79
	 * @see org.eclipse.ui.dialogs.ISelectionValidator#isValid(java.lang.Object)
80
	 */
81
	public IStatus validate(Object[] elements) {
82
		if (isValid(elements)) {
83
			return fgOKStatus;
84
		}
85
		return fgErrorStatus;
86
	}
87
88
	private boolean isOfAcceptedType(Object o) {
89
		for (int i = 0; i < fAcceptedTypes.length; i++) {
90
			if (fAcceptedTypes[i].isInstance(o)) {
91
				return true;
92
			}
93
		}
94
		return false;
95
	}
96
97
	private boolean isRejectedElement(Object elem) {
98
		return (fRejectedElements != null) && fRejectedElements.contains(elem);
99
	}
100
101
	/**
102
	 * @param elem
103
	 *            the element to test
104
	 * @return returns if the selected element is valid
105
	 */
106
	protected boolean isSelectedValid(Object elem) {
107
		return true;
108
	}
109
110
	private boolean isValid(Object[] selection) {
111
		if (selection.length == 0) {
112
			return false;
113
		}
114
115
		if (!fAllowMultipleSelection && selection.length != 1) {
116
			return false;
117
		}
118
119
		for (int i = 0; i < selection.length; i++) {
120
			Object o = selection[i];
121
			if (!isOfAcceptedType(o) || isRejectedElement(o)
122
					|| !isSelectedValid(o)) {
123
				return false;
124
			}
125
		}
126
		return true;
127
	}
128
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/TypedViewerFilter.java (+83 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2006 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
/*******************************************************************************
12
 * Copyright (c) 2008 Sybase Inc. and others.
13
 * 
14
 * All rights reserved. This program and the accompanying materials
15
 * are made available under the terms of the Eclipse Public License v1.0
16
 * which accompanies this distribution, and is available at
17
 * http://www.eclipse.org/legal/epl-v10.html
18
 * 
19
 * Contributors:
20
 *     Feng Wang (Sybase) - Copy from {@link org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter}
21
 *******************************************************************************/
22
23
package org.eclipse.mtj.ui.internal.wizards.template;
24
25
import org.eclipse.core.runtime.Assert;
26
27
import org.eclipse.jface.viewers.Viewer;
28
import org.eclipse.jface.viewers.ViewerFilter;
29
30
/**
31
 * Viewer filter used in selection dialogs.
32
 */
33
public class TypedViewerFilter extends ViewerFilter {
34
35
	private Class<?>[] fAcceptedTypes;
36
	private Object[] fRejectedElements;
37
38
	/**
39
	 * Creates a filter that only allows elements of gives types.
40
	 * 
41
	 * @param acceptedTypes
42
	 *            The types of accepted elements
43
	 */
44
	public TypedViewerFilter(Class<?>[] acceptedTypes) {
45
		this(acceptedTypes, null);
46
	}
47
48
	/**
49
	 * Creates a filter that only allows elements of gives types, but not from a
50
	 * list of rejected elements.
51
	 * 
52
	 * @param acceptedTypes
53
	 *            Accepted elements must be of this types
54
	 * @param rejectedElements
55
	 *            Element equals to the rejected elements are filtered out
56
	 */
57
	public TypedViewerFilter(Class<?>[] acceptedTypes, Object[] rejectedElements) {
58
		Assert.isNotNull(acceptedTypes);
59
		fAcceptedTypes = acceptedTypes;
60
		fRejectedElements = rejectedElements;
61
	}
62
63
	/**
64
	 * @see ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
65
	 *      java.lang.Object, java.lang.Object)
66
	 */
67
	public boolean select(Viewer viewer, Object parentElement, Object element) {
68
		if (fRejectedElements != null) {
69
			for (int i = 0; i < fRejectedElements.length; i++) {
70
				if (element.equals(fRejectedElements[i])) {
71
					return false;
72
				}
73
			}
74
		}
75
		for (int i = 0; i < fAcceptedTypes.length; i++) {
76
			if (fAcceptedTypes[i].isInstance(element)) {
77
				return true;
78
			}
79
		}
80
		return false;
81
	}
82
83
}
(-)src/org/eclipse/mtj/ui/internal/wizards/template/messages.properties (+29 lines)
Line 0 Link Here
1
###############################################################################
2
# Copyright (c) 2008 Sybase Inc. and others.
3
# 
4
# All rights reserved. This program and the accompanying materials
5
# are made available under the terms of the Eclipse Public License v1.0
6
# which accompanies this distribution, and is available at
7
# http://www.eclipse.org/legal/epl-v10.html
8
# 
9
# Contributors:
10
#     Feng Wang (Sybase) - initial implementation
11
###############################################################################
12
WizardTemplateSelectionPage_title = Templates
13
WizardTemplateSelectionPage_desc = Select one of the available templates to generate a Midlet.
14
WizardTemplateSelectionPage_templates = &Available Templates:
15
WizardTemplateSelectionPage_JavaRoot = Java Source Folder:
16
WizardTemplateSelectionPage_ResourceRoot = Resource Folder:
17
WizardTemplateSelectionPage_SourceFolderBrowse = Browse...
18
19
MewMidletFromTemplateWizard_windowTitle = New Midlet with Templates
20
MewMidletFromTemplateWizard_error_title = Error
21
MewMidletFromTemplateWizard_error_nothingSelected = You should select a project
22
23
MewMidletFromTemplateWizard_ChooseSourceContainerDialog_title = Source Folder Selection
24
MewMidletFromTemplateWizard_ChooseSourceContainerDialog_description = &Choose a source folder:
25
26
Validation_NotSourceFolder=Folder ''{0}'' is not a source folder
27
Validation_NotMTJProject=Project ''{0}'' is not a MTJ Midlet Suite project
28
29
ErrorDialogTitle_duringCopy="copy files"\ No newline at end of file
(-)src/org/eclipse/mtj/ui/internal/template/MidletTemplateWizardPage.java (+49 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.template;
14
15
import org.eclipse.jface.dialogs.Dialog;
16
import org.eclipse.jface.wizard.WizardPage;
17
import org.eclipse.mtj.ui.template.MidletTemplate;
18
import org.eclipse.mtj.ui.template.TemplateOption;
19
import org.eclipse.swt.SWT;
20
import org.eclipse.swt.layout.GridLayout;
21
import org.eclipse.swt.widgets.Composite;
22
23
public class MidletTemplateWizardPage extends WizardPage {
24
25
	private MidletTemplate template;
26
27
	public MidletTemplateWizardPage(MidletTemplate template) {
28
		super("");
29
		this.template = template;
30
		setTitle(template.getName());
31
		setDescription(TemplateMessages.MidletTemplateWizardPage_desc);
32
	}
33
34
	public void createControl(Composite parent) {
35
		Composite container = new Composite(parent, SWT.NULL);
36
		GridLayout layout = new GridLayout();
37
		layout.numColumns = 2;
38
		layout.verticalSpacing = 9;
39
		container.setLayout(layout);
40
		// Create control for each template option
41
		for (TemplateOption option : template.getOptions()) {
42
			option.createControl(container, 2);
43
		}
44
45
		setControl(container);
46
		Dialog.applyDialogFont(container);
47
	}
48
49
}
(-)src/org/eclipse/mtj/ui/internal/template/TemplateMessages.java (+33 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.template;
14
15
import org.eclipse.osgi.util.NLS;
16
17
public class TemplateMessages extends NLS {
18
	private static final String BUNDLE_NAME = "org.eclipse.mtj.ui.internal.template.messages";//$NON-NLS-N$
19
20
	public static String MidletTemplateWizard_title;
21
22
	public static String MidletTemplateWizardPage_desc;
23
24
	public static String Option_Package_label;
25
26
	public static String Option_Package_defaultValue;
27
28
	public static String Template_descriptionNotAvailable;
29
30
	static {
31
		NLS.initializeMessages(BUNDLE_NAME, TemplateMessages.class);
32
	}
33
}
(-)src/org/eclipse/mtj/ui/internal/template/TemplateWizardProxy.java (+170 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.template;
14
15
import java.util.MissingResourceException;
16
import java.util.ResourceBundle;
17
18
import org.eclipse.core.runtime.CoreException;
19
import org.eclipse.core.runtime.IConfigurationElement;
20
import org.eclipse.core.runtime.Platform;
21
import org.eclipse.jdt.core.IPackageFragmentRoot;
22
import org.eclipse.jface.resource.ImageDescriptor;
23
import org.eclipse.mtj.ui.template.MidletTemplateWizard;
24
import org.eclipse.ui.plugin.AbstractUIPlugin;
25
import org.osgi.framework.Bundle;
26
27
/**
28
 * This class is a proxy of the real template wizard.
29
 * 
30
 * @author wangf
31
 * 
32
 */
33
public class TemplateWizardProxy {
34
35
	public static final String ATT_NAME = "name"; //$NON-NLS-1$
36
	public static final String TAG_DESCRIPTION = "description"; //$NON-NLS-1$
37
	public static final String ATT_ID = "id"; //$NON-NLS-1$
38
	public static final String ATT_CLASS = "class"; //$NON-NLS-1$
39
	public static final String ATT_ICON = "icon";
40
41
	private IConfigurationElement wizardElement;
42
43
	private String description;
44
45
	private ImageDescriptor imageDescriptor;
46
47
	public TemplateWizardProxy(IConfigurationElement e) {
48
		this.wizardElement = e;
49
	}
50
51
	/**
52
	 * This method is used by UI to display the Midlet template name.
53
	 */
54
	@Override
55
	public String toString() {
56
		return wizardElement.getAttribute(ATT_NAME);
57
	}
58
59
	/**
60
	 * Create MidletTemplateWizard from the IConfigurationElement
61
	 * 
62
	 * @param javaRoot -
63
	 *            the Java source folder of the MTJ Midlet suite project. User
64
	 *            can choose this folder on the wizard page.
65
	 * @param resourceRoot -
66
	 *            the resource folder of the MTJ Midlet suite project. User can
67
	 *            choose this folder on the wizard page.
68
	 * @return
69
	 * @throws CoreException
70
	 */
71
	public MidletTemplateWizard createWizard(IPackageFragmentRoot javaRoot,
72
			IPackageFragmentRoot resourceRoot) throws CoreException {
73
		// Create the wizard
74
		MidletTemplateWizard midletTemplateWizard = (MidletTemplateWizard) wizardElement
75
				.createExecutableExtension(ATT_CLASS);
76
		// Set the Java source folder and resource folder
77
		midletTemplateWizard.setJavaRoot(javaRoot);
78
		midletTemplateWizard.setResourceRoot(resourceRoot);
79
80
		return midletTemplateWizard;
81
	}
82
83
	/**
84
	 * Get the ImageDescriptor of the wizard.
85
	 * 
86
	 * @return
87
	 */
88
	public ImageDescriptor getIcon() {
89
		if (imageDescriptor == null) {
90
			String iconName = wizardElement.getAttribute(ATT_ICON);
91
			if (iconName == null) {
92
				return null;
93
			}
94
			imageDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
95
					wizardElement.getNamespaceIdentifier(), iconName);
96
		}
97
		return imageDescriptor;
98
	}
99
100
	/**
101
	 * Get the description of the wizard.
102
	 * 
103
	 * @return
104
	 */
105
	public String getDescription() {
106
		if (description == null) {
107
			IConfigurationElement[] children = wizardElement
108
					.getChildren(TAG_DESCRIPTION);
109
			if (children.length > 0) {
110
				description = expandDescription(children[0].getValue());
111
			} else {
112
				description = TemplateMessages.Template_descriptionNotAvailable;
113
			}
114
		}
115
		return description;
116
	}
117
118
	/**
119
	 * We allow replacement variables in description values as well. This is to
120
	 * allow extension template description reuse in project template wizards.
121
	 * Tokens in form '%token%' will be evaluated against the contributing
122
	 * plug-in's resource bundle. As before, to have '%' in the description, one
123
	 * need to add '%%'.
124
	 */
125
	private String expandDescription(String source) {
126
		if (source == null || source.length() == 0)
127
			return source;
128
		if (source.indexOf('%') == -1)
129
			return source;
130
131
		Bundle bundle = Platform.getBundle(wizardElement
132
				.getNamespaceIdentifier());
133
		if (bundle == null)
134
			return source;
135
136
		ResourceBundle resourceBundle = Platform.getResourceBundle(bundle);
137
		if (resourceBundle == null)
138
			return source;
139
		StringBuffer buf = new StringBuffer();
140
		boolean keyMode = false;
141
		int keyStartIndex = -1;
142
		for (int i = 0; i < source.length(); i++) {
143
			char c = source.charAt(i);
144
			if (c == '%') {
145
				char c2 = source.charAt(i + 1);
146
				if (c2 == '%') {
147
					i++;
148
					buf.append('%');
149
					continue;
150
				}
151
				if (keyMode) {
152
					keyMode = false;
153
					String key = source.substring(keyStartIndex, i);
154
					String value = key;
155
					try {
156
						value = resourceBundle.getString(key);
157
					} catch (MissingResourceException e) {
158
					}
159
					buf.append(value);
160
				} else {
161
					keyStartIndex = i + 1;
162
					keyMode = true;
163
				}
164
			} else if (!keyMode) {
165
				buf.append(c);
166
			}
167
		}
168
		return buf.toString();
169
	}
170
}
(-)src/org/eclipse/mtj/ui/internal/template/TemplateWizardRegistry.java (+55 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.template;
14
15
import java.util.ArrayList;
16
import java.util.List;
17
18
import org.eclipse.core.runtime.IConfigurationElement;
19
import org.eclipse.core.runtime.IExtensionRegistry;
20
import org.eclipse.core.runtime.Platform;
21
import org.eclipse.mtj.ui.internal.MTJUIPlugin;
22
23
/**
24
 * This class is used to retrieve all of the "midletTemplateWizard" extensions.
25
 * 
26
 * @author wangf
27
 * 
28
 */
29
public class TemplateWizardRegistry {
30
	public static final String MIDLET_TEMPLATE_WIZARD = "midletTemplateWizard";
31
32
	private TemplateWizardRegistry() {
33
	}
34
35
	/**
36
	 * Get all of the extensions of org.eclipse.mtj.ui.midletTemplateWizard
37
	 * extension point.
38
	 * 
39
	 * @return - a list of TemplateWizardProxy
40
	 */
41
	public static List<TemplateWizardProxy> getTemplateWizardProxies() {
42
		List<TemplateWizardProxy> proxies = new ArrayList<TemplateWizardProxy>();
43
44
		IExtensionRegistry registry = Platform.getExtensionRegistry();
45
		String pluginId = MTJUIPlugin.getDefault().getBundle()
46
				.getSymbolicName();
47
		IConfigurationElement[] elements = registry
48
				.getConfigurationElementsFor(pluginId, MIDLET_TEMPLATE_WIZARD);
49
		for (IConfigurationElement e : elements) {
50
			TemplateWizardProxy proxy = new TemplateWizardProxy(e);
51
			proxies.add(proxy);
52
		}
53
		return proxies;
54
	}
55
}
(-)src/org/eclipse/mtj/ui/internal/template/WizardNode.java (+58 lines)
Line 0 Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2008 Sybase Inc. and others.
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors:
10
 *     Feng Wang (Sybase) - initial implementation
11
 *******************************************************************************/
12
13
package org.eclipse.mtj.ui.internal.template;
14
15
import org.eclipse.core.runtime.CoreException;
16
import org.eclipse.core.runtime.IStatus;
17
import org.eclipse.jface.wizard.IWizard;
18
import org.eclipse.jface.wizard.IWizardNode;
19
import org.eclipse.jface.wizard.Wizard;
20
import org.eclipse.mtj.core.internal.MTJCorePlugin;
21
import org.eclipse.swt.graphics.Point;
22
23
public abstract class WizardNode implements IWizardNode {
24
25
	private IWizard wizard;
26
27
	public void dispose() {
28
		if (wizard != null) {
29
			wizard.dispose();
30
			wizard = null;
31
		}
32
	}
33
34
	public Point getExtent() {
35
		return new Point(-1, -1);
36
	}
37
38
	public IWizard getWizard() {
39
		if (wizard != null) {
40
			return wizard; // we've already created it
41
		}
42
		try {
43
			wizard = createWizard();
44
		} catch (CoreException e) {
45
			MTJCorePlugin.log(IStatus.ERROR, e);
46
			// may be convenient for template wizard extension developer.
47
			e.printStackTrace();
48
		} // create instance of target wizard
49
		return wizard;
50
	}
51
52
	protected abstract Wizard createWizard() throws CoreException;
53
54
	public boolean isContentCreated() {
55
		return wizard != null;
56
	}
57
58
}
(-)src/org/eclipse/mtj/ui/internal/template/messages.properties (+17 lines)
Line 0 Link Here
1
###############################################################################
2
# Copyright (c) 2008 Sybase Inc. and others.
3
# 
4
# All rights reserved. This program and the accompanying materials
5
# are made available under the terms of the Eclipse Public License v1.0
6
# which accompanies this distribution, and is available at
7
# http://www.eclipse.org/legal/epl-v10.html
8
# 
9
# Contributors:
10
#     Feng Wang (Sybase) - initial implementation
11
###############################################################################
12
MidletTemplateWizard_title = New Midlet with Templates
13
MidletTemplateWizardPage_desc=You may customize the following fields
14
Option_Package_label=Package name:
15
Option_Package_defaultValue=mtj.template
16
17
Template_descriptionNotAvailable=Description of the template is not available.\ No newline at end of file

Return to bug 239979