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

Collapse All | Expand All

(-)src/org/eclipse/mtj/internal/core/project/midp/MidletSuiteFactory.java (-62 / +131 lines)
Lines 22-28 Link Here
22
 *     David Marques (Motorola) - Fixing project creation configuration/profile.
22
 *     David Marques (Motorola) - Fixing project creation configuration/profile.
23
 *     Fernando Rocha(Motorola) - Update all Projects when a device is modified.
23
 *     Fernando Rocha(Motorola) - Update all Projects when a device is modified.
24
 *     David Aragao (Motorola) -  Problem when try to import a project without 
24
 *     David Aragao (Motorola) -  Problem when try to import a project without 
25
 *     							  copy the files to the workspace. [Bug - 270157]
25
 *     Fernando Rocha(Motorola) - Add the project properties							  copy the files to the workspace. [Bug - 270157]
26
 */
26
 */
27
package org.eclipse.mtj.internal.core.project.midp;
27
package org.eclipse.mtj.internal.core.project.midp;
28
28
Lines 34-39 Link Here
34
import java.util.ArrayList;
34
import java.util.ArrayList;
35
import java.util.Arrays;
35
import java.util.Arrays;
36
import java.util.HashMap;
36
import java.util.HashMap;
37
import java.util.List;
37
import java.util.Map;
38
import java.util.Map;
38
39
39
import org.eclipse.core.resources.IFile;
40
import org.eclipse.core.resources.IFile;
Lines 40-45 Link Here
40
import org.eclipse.core.resources.IFolder;
41
import org.eclipse.core.resources.IFolder;
41
import org.eclipse.core.resources.IProject;
42
import org.eclipse.core.resources.IProject;
42
import org.eclipse.core.resources.IProjectDescription;
43
import org.eclipse.core.resources.IProjectDescription;
44
import org.eclipse.core.resources.IResource;
43
import org.eclipse.core.resources.ResourcesPlugin;
45
import org.eclipse.core.resources.ResourcesPlugin;
44
import org.eclipse.core.runtime.CoreException;
46
import org.eclipse.core.runtime.CoreException;
45
import org.eclipse.core.runtime.IProgressMonitor;
47
import org.eclipse.core.runtime.IProgressMonitor;
Lines 47-53 Link Here
47
import org.eclipse.core.runtime.NullProgressMonitor;
49
import org.eclipse.core.runtime.NullProgressMonitor;
48
import org.eclipse.core.runtime.Preferences;
50
import org.eclipse.core.runtime.Preferences;
49
import org.eclipse.core.runtime.SubProgressMonitor;
51
import org.eclipse.core.runtime.SubProgressMonitor;
52
import org.eclipse.jdt.core.IClasspathEntry;
50
import org.eclipse.jdt.core.IJavaProject;
53
import org.eclipse.jdt.core.IJavaProject;
54
import org.eclipse.jdt.core.IPackageFragment;
55
import org.eclipse.jdt.core.IPackageFragmentRoot;
51
import org.eclipse.jdt.core.JavaCore;
56
import org.eclipse.jdt.core.JavaCore;
52
import org.eclipse.mtj.core.MTJCore;
57
import org.eclipse.mtj.core.MTJCore;
53
import org.eclipse.mtj.core.project.IMTJProject;
58
import org.eclipse.mtj.core.project.IMTJProject;
Lines 56-65 Link Here
56
import org.eclipse.mtj.core.project.runtime.MTJRuntimeList;
61
import org.eclipse.mtj.core.project.runtime.MTJRuntimeList;
57
import org.eclipse.mtj.core.sdk.device.IDevice;
62
import org.eclipse.mtj.core.sdk.device.IDevice;
58
import org.eclipse.mtj.core.sdk.device.IDeviceRegistryListener;
63
import org.eclipse.mtj.core.sdk.device.IDeviceRegistryListener;
59
import org.eclipse.mtj.core.sdk.device.midp.IMIDPAPI;
60
import org.eclipse.mtj.core.sdk.device.midp.IMIDPDevice;
64
import org.eclipse.mtj.core.sdk.device.midp.IMIDPDevice;
61
import org.eclipse.mtj.internal.core.IMTJCoreConstants;
65
import org.eclipse.mtj.internal.core.IMTJCoreConstants;
66
import org.eclipse.mtj.internal.core.l10n.L10nApi;
62
import org.eclipse.mtj.internal.core.util.ColonDelimitedProperties;
67
import org.eclipse.mtj.internal.core.util.ColonDelimitedProperties;
68
import org.eclipse.mtj.internal.core.util.Utils;
63
import org.eclipse.mtj.internal.core.util.log.MTJLogger;
69
import org.eclipse.mtj.internal.core.util.log.MTJLogger;
64
70
65
/**
71
/**
Lines 87-112 Link Here
87
         */
93
         */
88
        private static final String BIN_FOLDER_NAME = "bin"; //$NON-NLS-1$
94
        private static final String BIN_FOLDER_NAME = "bin"; //$NON-NLS-1$
89
95
90
        /**
91
         * 
92
         */
93
        private static final String CONFIGURATION_VERSION_1_0 = "CLDC-1.0"; //$NON-NLS-1$
94
95
        /**
96
         * 
97
         */
98
        private static final String MIDLET_DEFAULT_NAME_END = " MIDlet Suite"; //$NON-NLS-1$
99
100
        /**
101
         * 
102
         */
103
        private static final String MIDLET_DEFAULT_VENDOR = "MIDlet Suite Vendor"; //$NON-NLS-1$
104
105
        /**
106
         * 
107
         */
108
        private static final String MIDLET_INITIAL_VERSION_1_0_0 = "1.0.0"; //$NON-NLS-1$
109
110
        private IMIDPDevice device;
96
        private IMIDPDevice device;
111
97
112
        private String jadFileName;
98
        private String jadFileName;
Lines 117-122 Link Here
117
103
118
        private IProject project;
104
        private IProject project;
119
105
106
        private Map<String, String> properties;
107
108
        private boolean localizationEnable;
109
110
        private String propertiesFolderName;
111
112
        private String packageName;
113
114
        private boolean jmUnitSupportEnable;
115
120
        /**
116
        /**
121
         * Construct a new runnable for MIDlet suite creation.
117
         * Construct a new runnable for MIDlet suite creation.
122
         * 
118
         * 
Lines 138-143 Link Here
138
        }
134
        }
139
135
140
        /**
136
        /**
137
         * @return the localizationEnable
138
         */
139
        public boolean isLocalizationEnable() {
140
            return localizationEnable;
141
        }
142
143
        /**
144
         * @return the jmUnitSupportEnable
145
         */
146
        public boolean isJMUnitSupportEnable() {
147
            return jmUnitSupportEnable;
148
        }
149
150
        /**
141
         * Run the specified runnable using the specified progress monitor.
151
         * Run the specified runnable using the specified progress monitor.
142
         * 
152
         * 
143
         * @param monitor the monitor used to report progress
153
         * @param monitor the monitor used to report progress
Lines 150-155 Link Here
150
                // Configure the project
160
                // Configure the project
151
                IMidletSuiteProject suite = getMidletSuiteProject(javaProject);
161
                IMidletSuiteProject suite = getMidletSuiteProject(javaProject);
152
162
163
                // Create the localization data
164
                createL10nData(suite, monitor);
165
153
                suite.setJadFileName(jadFileName);
166
                suite.setJadFileName(jadFileName);
154
                addNatures(monitor);
167
                addNatures(monitor);
155
168
Lines 166-171 Link Here
166
                suite.saveMetaData();
179
                suite.saveMetaData();
167
                // Adds the device container into classpath
180
                // Adds the device container into classpath
168
                suite.refreshClasspath(monitor);
181
                suite.refreshClasspath(monitor);
182
                IJavaProject javaProject2 = suite.getJavaProject();
183
                for(IClasspathEntry r : javaProject2.getRawClasspath()) {
184
                    System.out.println(r.getPath().toString());
185
                }
169
            } catch (CoreException e) {
186
            } catch (CoreException e) {
170
                throw new InvocationTargetException(e);
187
                throw new InvocationTargetException(e);
171
            } catch (IOException e) {
188
            } catch (IOException e) {
Lines 173-178 Link Here
173
            }
190
            }
174
        }
191
        }
175
192
193
        private void createL10nData(IMidletSuiteProject suite,
194
                IProgressMonitor monitor) throws CoreException, IOException {
195
            IProject project = suite.getProject();
196
197
            if (this.localizationEnable) {
198
                IFolder newSource = project.getFolder(propertiesFolderName);
199
                if (!newSource.exists()) {
200
                    newSource.create(true, true, monitor);
201
                }
202
                project.refreshLocal(IResource.DEPTH_ONE, monitor);
203
204
                List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
205
                entries.addAll(Arrays.asList(javaProject.getRawClasspath()));
206
207
                IClasspathEntry[] array = entries
208
                        .toArray(new IClasspathEntry[entries.size()]);
209
                if (!javaProject.hasClasspathCycle(array)) {
210
                    javaProject.setRawClasspath(array, monitor);
211
                }
212
213
                IResource[] sources = Utils.getSourceFolders(javaProject);
214
                for (int i = 0; i < sources.length; i++) {
215
                    IPackageFragmentRoot source = javaProject
216
                            .getPackageFragmentRoot(sources[i]);
217
                    if (source.exists()) {
218
                        IPackageFragment packageFragment = source
219
                                .createPackageFragment(packageName, true,
220
                                        monitor);
221
                        L10nApi.createLocalizationFile(project, newSource
222
                                .getProjectRelativePath(), packageFragment);
223
                        javaProject.getProject().refreshLocal(
224
                                IResource.DEPTH_INFINITE,
225
                                new NullProgressMonitor());
226
                        L10nApi.createLocalizationApi(project, packageFragment,
227
                                newSource.getProjectRelativePath());
228
                        javaProject.getProject().refreshLocal(
229
                                IResource.DEPTH_INFINITE,
230
                                new NullProgressMonitor());
231
                        break;
232
                    }
233
                }
234
            }
235
        }
236
176
        /**
237
        /**
177
         * @param preprocessEnable the preprocessEnable to set
238
         * @param preprocessEnable the preprocessEnable to set
178
         */
239
         */
Lines 181-186 Link Here
181
        }
242
        }
182
243
183
        /**
244
        /**
245
         * @param localizationEnable the localizationEnable to set
246
         */
247
        public void setLocalizationEnabled(boolean localizationEnable) {
248
            this.localizationEnable = localizationEnable;
249
        }
250
251
        /**
252
         * @param jmUnitSupportEnable the jmUnitSupportEnable to set
253
         */
254
        public void setJMUnitSupport(boolean jmUnitSupportEnable) {
255
            this.jmUnitSupportEnable = jmUnitSupportEnable;
256
        }
257
258
        /**
184
         * Add the specified nature to the list of natures if it is not already
259
         * Add the specified nature to the list of natures if it is not already
185
         * in the list.
260
         * in the list.
186
         * 
261
         * 
Lines 222-227 Link Here
222
                                IMTJCoreConstants.J2ME_PREPROCESSING_NATURE_ID);
297
                                IMTJCoreConstants.J2ME_PREPROCESSING_NATURE_ID);
223
            }
298
            }
224
299
300
            if (isLocalizationEnable()) {
301
                updated = updated
302
                        | addNatureIfNecessary(natures,
303
                                IMTJCoreConstants.L10N_NATURE_ID);
304
            }
305
306
            if (isJMUnitSupportEnable()) {
307
                updated = updated
308
                        | addNatureIfNecessary(natures,
309
                                IMTJCoreConstants.JMUNIT_NATURE_ID);
310
            }
311
225
            if (updated) {
312
            if (updated) {
226
                IProgressMonitor submonitor = new SubProgressMonitor(monitor, 1);
313
                IProgressMonitor submonitor = new SubProgressMonitor(monitor, 1);
227
                desc.setNatureIds(natures.toArray(new String[natures.size()]));
314
                desc.setNatureIds(natures.toArray(new String[natures.size()]));
Lines 283-299 Link Here
283
        }
370
        }
284
371
285
        /**
372
        /**
286
         * Return the version of the configuration from the device or
287
         * <code>null</code> if the version cannot be determined.
288
         * 
289
         * @return
290
         */
291
        private String getConfigurationVersion() {
292
            IMIDPAPI api = device.getCLDCAPI();
293
            return (api == null) ? CONFIGURATION_VERSION_1_0 : api.toString();
294
        }
295
296
        /**
297
         * @see org.eclipse.mtj.core.project.midp.IMidletSuiteProject#getDefaultApplicationDescriptorProperties()
373
         * @see org.eclipse.mtj.core.project.midp.IMidletSuiteProject#getDefaultApplicationDescriptorProperties()
298
         */
374
         */
299
        private ColonDelimitedProperties getDefaultApplicationDescriptorProperties(
375
        private ColonDelimitedProperties getDefaultApplicationDescriptorProperties(
Lines 305-330 Link Here
305
                    .getJarFilename());
381
                    .getJarFilename());
306
382
307
            // Couple of names...
383
            // Couple of names...
308
            descriptor.setProperty(IJADConstants.JAD_MIDLET_NAME, project
384
            descriptor.setProperty(IJADConstants.JAD_MIDLET_NAME, properties
309
                    .getName()
385
                    .get(IJADConstants.JAD_MIDLET_NAME));
310
                    + MIDLET_DEFAULT_NAME_END);
386
            descriptor.setProperty(IJADConstants.JAD_MIDLET_VENDOR, properties
311
            descriptor.setProperty(IJADConstants.JAD_MIDLET_VENDOR,
387
                    .get(IJADConstants.JAD_MIDLET_VENDOR));
312
                    MIDLET_DEFAULT_VENDOR);
388
            descriptor.setProperty(IJADConstants.JAD_MIDLET_VERSION, properties
313
            descriptor.setProperty(IJADConstants.JAD_MIDLET_VERSION,
389
                    .get(IJADConstants.JAD_MIDLET_VERSION));
314
                    MIDLET_INITIAL_VERSION_1_0_0);
315
390
316
            // Platform information
391
            // Platform information
317
            String configVersion = getConfigurationVersion();
392
            descriptor.setProperty(IJADConstants.JAD_MICROEDITION_CONFIG,
318
            if (configVersion != null) {
393
                    properties.get(IJADConstants.JAD_MICROEDITION_CONFIG));
319
                descriptor.setProperty(IJADConstants.JAD_MICROEDITION_CONFIG,
320
                        configVersion);
321
            }
322
394
323
            String profileVersion = getProfileVersion();
395
            descriptor.setProperty(IJADConstants.JAD_MICROEDITION_PROFILE,
324
            if (profileVersion != null) {
396
                    properties.get(IJADConstants.JAD_MICROEDITION_PROFILE));
325
                descriptor.setProperty(IJADConstants.JAD_MICROEDITION_PROFILE,
326
                        profileVersion);
327
            }
328
397
329
            return descriptor;
398
            return descriptor;
330
        }
399
        }
Lines 371-388 Link Here
371
        }
440
        }
372
441
373
        /**
442
        /**
374
         * Return the version of the profile from the device or
375
         * <code>null</code> if the version cannot be determined.
376
         * 
377
         * @return
378
         */
379
        private String getProfileVersion() {
380
            IMIDPAPI api = device.getMIDPAPI();
381
382
            return (api == null) ? null : api.toString();
383
        }
384
385
        /**
386
         * Set the necessary java project options.
443
         * Set the necessary java project options.
387
         * 
444
         * 
388
         * @param monitor
445
         * @param monitor
Lines 409-414 Link Here
409
            IMTJProject midletprj = getMidletSuiteProject(javaProject);
466
            IMTJProject midletprj = getMidletSuiteProject(javaProject);
410
            midletprj.saveMetaData();
467
            midletprj.saveMetaData();
411
        }
468
        }
469
470
        public void setProperties(Map<String, String> properties) {
471
            this.properties = properties;
472
        }
473
474
        public void setPropertiesFolderName(String propertiesFolderName) {
475
            this.propertiesFolderName = propertiesFolderName;
476
        }
477
478
        public void setPackageName(String packageName) {
479
            this.packageName = packageName;
480
        }
412
    }
481
    }
413
482
414
    // Storage of the previously created MIDlet suite projects
483
    // Storage of the previously created MIDlet suite projects
(-)src/org/eclipse/mtj/internal/core/l10n/Messages.java (-2 / +4 lines)
Lines 7-13 Link Here
7
 * http://www.eclipse.org/legal/epl-v10.html
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
8
 * 
9
 * Contributors:
9
 * Contributors:
10
 *     David Marques (Motorola) - Initial version                     
10
 *     David Marques  (Motorola) - Initial version                     
11
 *     Fernando Rocha (Motorola) - Add new message unableToCreateL10nFile [Bug 261873]
11
 */
12
 */
12
package org.eclipse.mtj.internal.core.l10n;
13
package org.eclipse.mtj.internal.core.l10n;
13
14
Lines 21-27 Link Here
21
 */
22
 */
22
public class Messages extends NLS {
23
public class Messages extends NLS {
23
24
24
    public static String L10nBuilder_BuildingLocalizationData;
25
    public static String L10nApi_unableToCreateL10nFile;
26
	public static String L10nBuilder_BuildingLocalizationData;
25
    public static String L10nBuilder_clean_CleaningOldProperties;
27
    public static String L10nBuilder_clean_CleaningOldProperties;
26
    public static String L10nBuilder_InvalidModel;
28
    public static String L10nBuilder_InvalidModel;
27
    public static String L10nBuilder_ErrorParsingLocalizationData;
29
    public static String L10nBuilder_ErrorParsingLocalizationData;
(-)src/org/eclipse/mtj/internal/core/l10n/messages.properties (+1 lines)
Lines 1-3 Link Here
1
L10nApi_unableToCreateL10nFile=Unable to resolve Localization Data location
1
L10nBuilder_BuildingLocalizationData=Building Localization Data
2
L10nBuilder_BuildingLocalizationData=Building Localization Data
2
L10nBuilder_clean_CleaningOldProperties=Cleaning old properties
3
L10nBuilder_clean_CleaningOldProperties=Cleaning old properties
3
L10nBuilder_InvalidModel=Localization Model is not valid.
4
L10nBuilder_InvalidModel=Localization Model is not valid.
(-)src/org/eclipse/mtj/internal/core/l10n/L10nApi.java (-16 / +50 lines)
Lines 7-21 Link Here
7
 * http://www.eclipse.org/legal/epl-v10.html
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
8
 * 
9
 * Contributors:
9
 * Contributors:
10
 *     David Marques (Motorola) - Initial version
10
 *     David Marques  (Motorola) - Initial version
11
 *     David Marques (Motorola) - Fixing propeties folder path
11
 *     David Marques  (Motorola) - Fixing propeties folder path
12
 *     David Marques (Motorola) - Removing old classes from L10n API
12
 *     David Marques  (Motorola) - Removing old classes from L10n API
13
 *                                upon API creation.
13
 *                                 upon API creation.
14
 *     David Marques (Motorola) - Generating keys on upper case.
14
 *     David Marques  (Motorola) - Generating keys on upper case.
15
 *     David Marques (Motorola) - Refactoring to support default locale.
15
 *     David Marques  (Motorola) - Refactoring to support default locale.
16
 *     Fernando Rocha (Motorola) - Method for create the localization file [Bug 261873].
16
 */
17
 */
17
package org.eclipse.mtj.internal.core.l10n;
18
package org.eclipse.mtj.internal.core.l10n;
18
19
20
import java.io.IOException;
19
import java.io.InputStream;
21
import java.io.InputStream;
20
import java.util.ArrayList;
22
import java.util.ArrayList;
21
import java.util.HashMap;
23
import java.util.HashMap;
Lines 32-40 Link Here
32
import org.eclipse.core.runtime.NullProgressMonitor;
34
import org.eclipse.core.runtime.NullProgressMonitor;
33
import org.eclipse.core.runtime.Path;
35
import org.eclipse.core.runtime.Path;
34
import org.eclipse.jdt.core.ICompilationUnit;
36
import org.eclipse.jdt.core.ICompilationUnit;
37
import org.eclipse.jdt.core.IJavaElement;
35
import org.eclipse.jdt.core.IJavaProject;
38
import org.eclipse.jdt.core.IJavaProject;
36
import org.eclipse.jdt.core.IPackageFragment;
39
import org.eclipse.jdt.core.IPackageFragment;
37
import org.eclipse.jdt.core.JavaCore;
40
import org.eclipse.jdt.core.JavaCore;
41
import org.eclipse.jdt.core.JavaModelException;
42
import org.eclipse.jface.text.Document;
38
import org.eclipse.mtj.core.MTJCore;
43
import org.eclipse.mtj.core.MTJCore;
39
import org.eclipse.mtj.internal.core.text.IDocumentElementNode;
44
import org.eclipse.mtj.internal.core.text.IDocumentElementNode;
40
import org.eclipse.mtj.internal.core.text.l10n.L10nEntry;
45
import org.eclipse.mtj.internal.core.text.l10n.L10nEntry;
Lines 85-94 Link Here
85
    public static String buildL10nConstantsClass(IProject project,
90
    public static String buildL10nConstantsClass(IProject project,
86
            IPackageFragment _package) throws CoreException {
91
            IPackageFragment _package) throws CoreException {
87
        InputStream stream = MTJCore.getResourceAsStream(new Path(
92
        InputStream stream = MTJCore.getResourceAsStream(new Path(
88
                "templates/L10nConstants.java.template"));
93
                "templates/L10nConstants.java.template")); //$NON-NLS-1$
89
        if (stream == null) {
94
        if (stream == null) {
90
            MTJStatusHandler.throwCoreException(IStatus.ERROR, -999,
95
            MTJStatusHandler.throwCoreException(IStatus.ERROR, -999,
91
                    "Unable to load templates/L10nResources.java.template.");
96
                    "Unable to load templates/L10nResources.java.template."); //$NON-NLS-1$
92
        }
97
        }
93
98
94
        StringBuffer localesBuffer = new StringBuffer();
99
        StringBuffer localesBuffer = new StringBuffer();
Lines 123-134 Link Here
123
        Map<String, String> map = new HashMap<String, String>();
128
        Map<String, String> map = new HashMap<String, String>();
124
        String packName = _package.getElementName();
129
        String packName = _package.getElementName();
125
        if (packName != null && packName.length() > 0x00) {
130
        if (packName != null && packName.length() > 0x00) {
126
            map.put(PACKAGE, NLS.bind("package {0};", packName));
131
            map.put(PACKAGE, NLS.bind("package {0};", packName)); //$NON-NLS-1$
127
        } else {
132
        } else {
128
            map.put(PACKAGE, Utils.EMPTY_STRING);
133
            map.put(PACKAGE, Utils.EMPTY_STRING);
129
        }
134
        }
130
        map.put("locales", localesBuffer.toString());
135
        map.put("locales", localesBuffer.toString()); //$NON-NLS-1$
131
        map.put("keys", constntBuffer.toString());
136
        map.put("keys", constntBuffer.toString()); //$NON-NLS-1$
132
137
133
        StringBuffer buffer = new StringBuffer(Utils.getStreamContent(stream));
138
        StringBuffer buffer = new StringBuffer(Utils.getStreamContent(stream));
134
        String code = ReplaceableParametersProcessor.processReplaceableValues(
139
        String code = ReplaceableParametersProcessor.processReplaceableValues(
Lines 148-157 Link Here
148
    public static String buildL10nResourcesClass(IPackageFragment _package,
153
    public static String buildL10nResourcesClass(IPackageFragment _package,
149
            IPath _properties, String _defaultLocale) throws CoreException {
154
            IPath _properties, String _defaultLocale) throws CoreException {
150
        InputStream stream = MTJCore.getResourceAsStream(new Path(
155
        InputStream stream = MTJCore.getResourceAsStream(new Path(
151
                "templates/L10nResources.java.template"));
156
                "templates/L10nResources.java.template")); //$NON-NLS-1$
152
        if (stream == null) {
157
        if (stream == null) {
153
            MTJStatusHandler.throwCoreException(IStatus.ERROR, -999,
158
            MTJStatusHandler.throwCoreException(IStatus.ERROR, -999,
154
                    "Unable to load templates/L10nResources.java.template.");
159
                    "Unable to load templates/L10nResources.java.template."); //$NON-NLS-1$
155
        }
160
        }
156
161
157
        Map<String, String> map = new HashMap<String, String>();
162
        Map<String, String> map = new HashMap<String, String>();
Lines 158-164 Link Here
158
        map.put(DESTINATION, _properties.removeFirstSegments(1).toString());
163
        map.put(DESTINATION, _properties.removeFirstSegments(1).toString());
159
        String packName = _package.getElementName();
164
        String packName = _package.getElementName();
160
        if (packName != null && packName.length() > 0x00) {
165
        if (packName != null && packName.length() > 0x00) {
161
            map.put(PACKAGE, NLS.bind("package {0};", packName));
166
            map.put(PACKAGE, NLS.bind("package {0};", packName)); //$NON-NLS-1$
162
        } else {
167
        } else {
163
            map.put(PACKAGE, Utils.EMPTY_STRING);
168
            map.put(PACKAGE, Utils.EMPTY_STRING);
164
        }
169
        }
Lines 205-210 Link Here
205
    }
210
    }
206
211
207
    /**
212
    /**
213
     * Creates a Localization Data file into the specified destination.
214
     * 
215
     * @param _project target project.
216
     * @param _properties destination folder.
217
     * @param _package Class package name.
218
     * @return true upon success, false otherwise.
219
     * @throws IOException If any error occurs during class creation.
220
     * @throws JavaModelException If any java model error occurs.
221
     */
222
    public static boolean createLocalizationFile(IProject _project, IPath _properties,
223
            IJavaElement _package) throws JavaModelException, IOException {
224
225
        L10nModel model = new L10nModel(new Document(), false);
226
        L10nLocales locales = model.getLocales();
227
        locales.setDestination(_properties.toString());
228
        locales.setPackage(_package.getElementName());
229
230
        IPath path = _project.getLocation().append("Localization Data"); //$NON-NLS-1$
231
        IFile file = _project.getWorkspace().getRoot().getFileForLocation(path);
232
        if (file == null) {
233
            throw new IOException(Messages.L10nApi_unableToCreateL10nFile);
234
        }
235
        model.setUnderlyingResource(file);
236
        model.save();
237
238
        return file.exists();
239
    }
240
    
241
    /**
208
     * Writes a constant declaration.
242
     * Writes a constant declaration.
209
     * 
243
     * 
210
     * @param name constant name.
244
     * @param name constant name.
Lines 213-220 Link Here
213
     */
247
     */
214
    private static String writeStringConstantDeclaration(String name,
248
    private static String writeStringConstantDeclaration(String name,
215
            String value) {
249
            String value) {
216
        return NLS.bind("\t\tpublic static final String {0} = \"{1}\";\n",
250
        return NLS.bind("\t\tpublic static final String {0} = \"{1}\";\n", //$NON-NLS-1$
217
                new String[] { name.replace("-", "_"), value });
251
                new String[] { name.replace("-", "_"), value }); //$NON-NLS-1$ //$NON-NLS-2$
218
    }
252
    }
219
253
220
    /**
254
    /**
(-)src/org/eclipse/mtj/internal/core/sdk/device/DeviceRegistry.java (+6 lines)
Lines 12-17 Link Here
12
 *                                standards
12
 *                                standards
13
 *     Hugo Raniere (Motorola)  - Storing default preverifier
13
 *     Hugo Raniere (Motorola)  - Storing default preverifier
14
 *     David Aragao (Motorola)  - Fixing device removal.
14
 *     David Aragao (Motorola)  - Fixing device removal.
15
 *     Fernando Rocha(Motorola) - Loading the default devices [Bug 261873].
15
 */
16
 */
16
package org.eclipse.mtj.internal.core.sdk.device;
17
package org.eclipse.mtj.internal.core.sdk.device;
17
18
Lines 91-96 Link Here
91
    private DeviceRegistry() {
92
    private DeviceRegistry() {
92
        super();
93
        super();
93
        listenerList = new ArrayList<IDeviceRegistryListener>();
94
        listenerList = new ArrayList<IDeviceRegistryListener>();
95
        try {
96
			this.load();
97
		} catch (PersistenceException e) {
98
			e.printStackTrace();
99
		}
94
    }
100
    }
95
101
96
    /* (non-Javadoc)
102
    /* (non-Javadoc)
(-).project (+11 lines)
Line 0 Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>org.eclipse.mtj.core.library</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
	</buildSpec>
9
	<natures>
10
	</natures>
11
</projectDescription>
(-)src/org/eclipse/mtj/internal/ui/MTJUIMessages.java (-15 / +47 lines)
Lines 10-15 Link Here
10
 *     Diego Sandin (Motorola) - Initial implementation
10
 *     Diego Sandin (Motorola) - Initial implementation
11
 *     David Marques(Motorola) - Add midlet templates  
11
 *     David Marques(Motorola) - Add midlet templates  
12
 *     Fernando Rocha(Motorola)- Add jar message error   
12
 *     Fernando Rocha(Motorola)- Add jar message error   
13
 *     Fernando Rocha(Motorola)- Add messages for the new project wizard
13
 */
14
 */
14
package org.eclipse.mtj.internal.ui;
15
package org.eclipse.mtj.internal.ui;
15
16
Lines 936-941 Link Here
936
937
937
    private static final String BUNDLE_NAME = "org.eclipse.mtj.internal.ui.messages"; //$NON-NLS-1$
938
    private static final String BUNDLE_NAME = "org.eclipse.mtj.internal.ui.messages"; //$NON-NLS-1$
938
939
940
    public static final String MidletDefaultNameEnd = " MIDlet Suite"; //$NON-NLS-1$
941
    public static final String MidletDefaultVendor = "MIDlet Suite Vendor"; //$NON-NLS-1$
942
    public static final String MidletInitialVersion_1_0_0 = "1.0.0"; //$NON-NLS-1$
943
    public static final String MeConfigurationVersion = "CLDC-1.0"; //$NON-NLS-1$
944
    public static final String MeProfileVersion = "MIDP-2.1"; //$NON-NLS-1$
945
	
939
    public static String LibraryPropertyPage_description;
946
    public static String LibraryPropertyPage_description;
940
947
941
    public static String LibraryPropertyPage_unsavedchanges_button_discard;
948
    public static String LibraryPropertyPage_unsavedchanges_button_discard;
Lines 994-1016 Link Here
994
    public static String NewMidletProjectWizardPageOne_locationGroup_externalLocationRadio;
1001
    public static String NewMidletProjectWizardPageOne_locationGroup_externalLocationRadio;
995
    public static String NewMidletProjectWizardPageOne_locationGroup_projectLocation;
1002
    public static String NewMidletProjectWizardPageOne_locationGroup_projectLocation;
996
    public static String NewMidletProjectWizardPageOne_locationGroup_workspaceLocationRadio;
1003
    public static String NewMidletProjectWizardPageOne_locationGroup_workspaceLocationRadio;
1004
    public static String NewMidletProjectWizardPageOne_locationGroup_workingSetsButton;
1005
    public static String NewMidletProjectWizardPageOne_workingSet_null;
1006
    public static String NewMidletProjectWizardPageOne_workingSetGroup_contents;
1007
    public static String NewMidletProjectWizardPageOne_workingSetGroup_selection;
1008
    public static String NewMidletProjectWizardPageOne_workingSetGroup_select_button;
997
    public static String NewMidletProjectWizardPageOne_title;
1009
    public static String NewMidletProjectWizardPageOne_title;
1010
    
1011
    public static String NewMidletProjectWizardPageTwo_description;
1012
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_contents;
1013
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_midletName;
1014
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_midletVendor;
1015
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_midletVersion;
1016
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_meConfiguration;
1017
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_meProfile;
1018
    public static String NewMidletProjectWizardPageTwo_propertiesGroup_fieldEmpty;
1019
    public static String NewMidletProjectWizardPageTwo_optionsGroup_contents;
1020
    public static String NewMidletProjectWizardPageTwo_optionsGroup_enablePreprocessing;
1021
    public static String NewMidletProjectWizardPageTwo_optionsGroup_enableLocalization;
1022
    public static String NewMidletProjectWizardPageTwo_optionsGroup_propertiesFolder;
1023
    public static String NewMidletProjectWizardPageTwo_optionsGroup_package;
1024
    public static String NewMidletProjectWizardPageTwo_optionsGroup_packageEmpty;
1025
    public static String NewMidletProjectWizardPageTwo_optionsGroup_packageUpperCase;
1026
    public static String NewMidletProjectWizardPageTwo_optionsGroup_packageError;
1027
    public static String NewMidletProjectWizardPageTwo_optionsGroup_enableJMUnit;
1028
    public static String NewMidletProjectWizardPageTwo_title;
998
1029
999
    public static String NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_message;
1030
    public static String NewMidletProjectWizardPageThree_changeToNewProject_errordialog_message;
1000
    public static String NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_title;
1031
    public static String NewMidletProjectWizardPageThree_changeToNewProject_errordialog_title;
1001
    public static String NewMidletProjectWizardPageTwo_createBackup_error_1;
1032
    public static String NewMidletProjectWizardPageThree_createBackup_error_1;
1002
    public static String NewMidletProjectWizardPageTwo_createBackup_error_2;
1033
    public static String NewMidletProjectWizardPageThree_createBackup_error_2;
1003
    public static String NewMidletProjectWizardPageTwo_doRemoveProject_taskname;
1034
    public static String NewMidletProjectWizardPageThree_doRemoveProject_taskname;
1004
    public static String NewMidletProjectWizardPageTwo_performFinish_monitor_taskname;
1035
    public static String NewMidletProjectWizardPageThree_performFinish_monitor_taskname;
1005
    public static String NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_message;
1036
    public static String NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_message;
1006
    public static String NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_title;
1037
    public static String NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_title;
1007
    public static String NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotclasspath;
1038
    public static String NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotclasspath;
1008
    public static String NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotproject;
1039
    public static String NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotproject;
1009
    public static String NewMidletProjectWizardPageTwo_updateProject_errordialog_message;
1040
    public static String NewMidletProjectWizardPageThree_updateProject_errordialog_message;
1010
    public static String NewMidletProjectWizardPageTwo_updateProject_errordialog_title;
1041
    public static String NewMidletProjectWizardPageThree_updateProject_errordialog_title;
1011
    public static String NewMidletProjectWizardPageTwo_updateProject_fail_read_metadata;
1042
    public static String NewMidletProjectWizardPageThree_updateProject_fail_read_metadata;
1012
    public static String NewMidletProjectWizardPageTwo_updateProject_monitor_buildpath_name;
1043
    public static String NewMidletProjectWizardPageThree_updateProject_monitor_buildpath_name;
1013
    public static String NewMidletProjectWizardPageTwo_updateProject_taskname;
1044
    public static String NewMidletProjectWizardPageThree_updateProject_taskname;
1014
1045
1015
    public static String NewMidletProjectWizardPageLibrary_title;
1046
    public static String NewMidletProjectWizardPageLibrary_title;
1016
    public static String NewMidletProjectWizardPageLibrary_description;
1047
    public static String NewMidletProjectWizardPageLibrary_description;
Lines 1025-1030 Link Here
1025
    public static String NewMidletProjectWizardPageLibrary_HintTextGroup_title;
1056
    public static String NewMidletProjectWizardPageLibrary_HintTextGroup_title;
1026
1057
1027
    public static String ConfigurationSection_Description;
1058
    public static String ConfigurationSection_Description;
1059
1028
    
1060
    
1029
    static {
1061
    static {
1030
        // initialize resource bundle
1062
        // initialize resource bundle
(-)src/org/eclipse/mtj/internal/ui/wizards/l10n/LocalizationWizard.java (-39 / +3 lines)
Lines 10-16 Link Here
10
 *     David Marques (Motorola) - Initial version
10
 *     David Marques (Motorola) - Initial version
11
 *     David Marques (Motorola) - Adding canFinish method.
11
 *     David Marques (Motorola) - Adding canFinish method.
12
 *     David Marques (Motorola) - Refactoring Localization API.
12
 *     David Marques (Motorola) - Refactoring Localization API.
13
 *     David Marques (Motorola) - Refactoring to use L10nModel.                     
13
 *     David Marques (Motorola) - Refactoring to use L10nModel.
14
 *     Fernando Rocha(Motorola) - Refactoring Localization API.
14
 */
15
 */
15
package org.eclipse.mtj.internal.ui.wizards.l10n;
16
package org.eclipse.mtj.internal.ui.wizards.l10n;
16
17
Lines 16-26 Link Here
16
17
17
import java.io.IOException;
18
import java.io.IOException;
18
19
19
import org.eclipse.core.resources.IFile;
20
import org.eclipse.core.resources.IProject;
21
import org.eclipse.core.resources.IResource;
20
import org.eclipse.core.resources.IResource;
22
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.core.runtime.CoreException;
23
import org.eclipse.core.runtime.IPath;
24
import org.eclipse.core.runtime.NullProgressMonitor;
22
import org.eclipse.core.runtime.NullProgressMonitor;
25
import org.eclipse.jdt.core.IJavaElement;
23
import org.eclipse.jdt.core.IJavaElement;
26
import org.eclipse.jdt.core.IJavaProject;
24
import org.eclipse.jdt.core.IJavaProject;
Lines 25-36 Link Here
25
import org.eclipse.jdt.core.IJavaElement;
23
import org.eclipse.jdt.core.IJavaElement;
26
import org.eclipse.jdt.core.IJavaProject;
24
import org.eclipse.jdt.core.IJavaProject;
27
import org.eclipse.jdt.core.IPackageFragment;
25
import org.eclipse.jdt.core.IPackageFragment;
28
import org.eclipse.jdt.core.JavaModelException;
29
import org.eclipse.jface.text.Document;
30
import org.eclipse.jface.wizard.Wizard;
26
import org.eclipse.jface.wizard.Wizard;
31
import org.eclipse.mtj.internal.core.l10n.L10nApi;
27
import org.eclipse.mtj.internal.core.l10n.L10nApi;
32
import org.eclipse.mtj.internal.core.text.l10n.L10nLocales;
33
import org.eclipse.mtj.internal.core.text.l10n.L10nModel;
34
import org.eclipse.mtj.internal.ui.MTJUIMessages;
28
import org.eclipse.mtj.internal.ui.MTJUIMessages;
35
29
36
/**
30
/**
Lines 87-93 Link Here
87
81
88
        if (targetPack instanceof IPackageFragment) {
82
        if (targetPack instanceof IPackageFragment) {
89
            try {
83
            try {
90
                result = createLocalizationFile(properties
84
                result = L10nApi.createLocalizationFile(jProject.getProject(), properties
91
                        .getProjectRelativePath(), targetPack);
85
                        .getProjectRelativePath(), targetPack);
92
                jProject.getProject().refreshLocal(IResource.DEPTH_INFINITE,
86
                jProject.getProject().refreshLocal(IResource.DEPTH_INFINITE,
93
                        new NullProgressMonitor());
87
                        new NullProgressMonitor());
Lines 105-138 Link Here
105
        }
99
        }
106
        return result;
100
        return result;
107
    }
101
    }
108
109
    /**
110
     * Creates a Localization Data file into the specified destination.
111
     * 
112
     * @param _properties destination folder.
113
     * @param _package Class package name.
114
     * @return true upon success, false otherwise.
115
     * @throws IOException If any error occurs during class creation.
116
     * @throws JavaModelException If any java model error occurs.
117
     */
118
    private boolean createLocalizationFile(IPath _properties,
119
            IJavaElement _package) throws JavaModelException, IOException {
120
121
        L10nModel model = new L10nModel(new Document(), false);
122
        L10nLocales locales = model.getLocales();
123
        locales.setDestination(_properties.toString());
124
        locales.setPackage(_package.getElementName());
125
126
        IProject project = jProject.getProject();
127
        IPath path = project.getLocation().append("Localization Data"); //$NON-NLS-1$
128
        IFile file = project.getWorkspace().getRoot().getFileForLocation(path);
129
        if (file == null) {
130
            throw new IOException(
131
                    MTJUIMessages.LocalizationWizard_failed_createLocalizationFile);
132
        }
133
        model.setUnderlyingResource(file);
134
        model.save();
135
136
        return file.exists();
137
    }
138
}
102
}
(-)src/org/eclipse/mtj/internal/ui/wizards/projects/NewMidletProjectWizardPageTwo.java (-878 lines)
Lines 1-878 Link Here
1
/**
2
 * Copyright (c) 2008 Motorola.
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
 *     Diego Sandin (Motorola) - Initial version
11
 *     Feng Wang (Sybase)      - Add configurations into Metadata for Multi-Configs
12
 *                               support.
13
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
14
 */
15
package org.eclipse.mtj.internal.ui.wizards.projects;
16
17
import java.io.File;
18
import java.io.FileInputStream;
19
import java.io.FileOutputStream;
20
import java.io.IOException;
21
import java.io.InputStream;
22
import java.io.OutputStream;
23
import java.lang.reflect.InvocationTargetException;
24
import java.net.URI;
25
import java.net.URISyntaxException;
26
import java.util.ArrayList;
27
import java.util.HashSet;
28
import java.util.List;
29
import java.util.Map;
30
31
import org.eclipse.core.filesystem.EFS;
32
import org.eclipse.core.filesystem.IFileInfo;
33
import org.eclipse.core.filesystem.IFileStore;
34
import org.eclipse.core.resources.IFolder;
35
import org.eclipse.core.resources.IProject;
36
import org.eclipse.core.resources.IResource;
37
import org.eclipse.core.resources.IResourceStatus;
38
import org.eclipse.core.resources.IWorkspaceDescription;
39
import org.eclipse.core.resources.IWorkspaceRoot;
40
import org.eclipse.core.resources.ResourcesPlugin;
41
import org.eclipse.core.runtime.Assert;
42
import org.eclipse.core.runtime.CoreException;
43
import org.eclipse.core.runtime.IPath;
44
import org.eclipse.core.runtime.IProgressMonitor;
45
import org.eclipse.core.runtime.IStatus;
46
import org.eclipse.core.runtime.NullProgressMonitor;
47
import org.eclipse.core.runtime.OperationCanceledException;
48
import org.eclipse.core.runtime.Path;
49
import org.eclipse.core.runtime.Preferences;
50
import org.eclipse.core.runtime.Status;
51
import org.eclipse.core.runtime.SubProgressMonitor;
52
import org.eclipse.jdt.core.IClasspathEntry;
53
import org.eclipse.jdt.core.IJavaProject;
54
import org.eclipse.jdt.core.JavaCore;
55
import org.eclipse.jdt.ui.PreferenceConstants;
56
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
57
import org.eclipse.jface.dialogs.ErrorDialog;
58
import org.eclipse.jface.operation.IRunnableWithProgress;
59
import org.eclipse.jface.preference.IPreferenceStore;
60
import org.eclipse.mtj.core.MTJCore;
61
import org.eclipse.mtj.core.project.IMetaData;
62
import org.eclipse.mtj.core.project.ProjectType;
63
import org.eclipse.mtj.core.project.runtime.MTJRuntimeList;
64
import org.eclipse.mtj.core.sdk.device.IDevice;
65
import org.eclipse.mtj.core.sdk.device.midp.IMIDPDevice;
66
import org.eclipse.mtj.internal.core.IMTJCoreConstants;
67
import org.eclipse.mtj.internal.core.build.preprocessor.PreprocessorBuilder;
68
import org.eclipse.mtj.internal.core.project.midp.JavaMEClasspathContainer;
69
import org.eclipse.mtj.internal.core.project.midp.MidletSuiteFactory;
70
import org.eclipse.mtj.internal.ui.IMTJUIConstants;
71
import org.eclipse.mtj.internal.ui.MTJUIMessages;
72
import org.eclipse.mtj.internal.ui.util.ExceptionHandler;
73
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
74
75
/**
76
 * The New MIDlet Project Java Capability Wizard Page allows the user to
77
 * configure the build path and output location of the MIDlet Project. As
78
 * addition to the {@link JavaCapabilityConfigurationPage}, the wizard page does
79
 * an early project creation (so that linked folders can be defined).
80
 * 
81
 * @author Diego Madruga Sandin
82
 * @since 0.9
83
 */
84
public class NewMidletProjectWizardPageTwo extends
85
        JavaCapabilityConfigurationPage {
86
87
    private static final String FILENAME_CLASSPATH = ".classpath"; //$NON-NLS-1$
88
89
    private static final String FILENAME_PROJECT = ".project"; //$NON-NLS-1$
90
91
    /**
92
     * @param projectName
93
     * @param location
94
     * @return
95
     */
96
    private static URI getRealLocation(String projectName, URI location) {
97
        if (location == null) { // inside workspace
98
            try {
99
                URI rootLocation = MTJCore.getWorkspace().getRoot()
100
                        .getLocationURI();
101
102
                location = new URI(rootLocation.getScheme(), null, Path
103
                        .fromPortableString(rootLocation.getPath()).append(
104
                                projectName).toString(), null);
105
            } catch (URISyntaxException e) {
106
                Assert.isTrue(false, "Can't happen"); //$NON-NLS-1$
107
            }
108
        }
109
        return location;
110
    }
111
112
    public Boolean isAutobuild;
113
    private IProject currProject;
114
    private URI currProjectLocation;
115
    private File fDotClasspathBackup;
116
    private File fDotProjectBackup;
117
    private NewMidletProjectWizardPageOne firstPage;
118
    private HashSet<IFileStore> fOrginalFolders;
119
120
    private boolean keepContent;
121
122
    private NewMidletProjectWizardPageLibrary pageLibrary;
123
124
    /**
125
     * Creates a new New MIDlet Project Java Capability Wizard Page.
126
     * 
127
     * @param workbench
128
     */
129
    public NewMidletProjectWizardPageTwo(NewMidletProjectWizardPageOne page,
130
            NewMidletProjectWizardPageLibrary pageLibrary) {
131
        this.currProjectLocation = null;
132
        this.currProject = null;
133
        this.firstPage = page;
134
        this.pageLibrary = pageLibrary;
135
        isAutobuild = null;
136
    }
137
138
    /**
139
     * Called from the wizard on cancel.
140
     */
141
    public void performCancel() {
142
        if (currProject != null) {
143
            removeProvisonalProject();
144
        }
145
    }
146
147
    /**
148
     * Called from the wizard on finish.
149
     * 
150
     * @param monitor the progress monitor
151
     * @throws CoreException thrown when the project creation or configuration
152
     *             failed
153
     * @throws InterruptedException thrown when the user canceled the project
154
     *             creation
155
     */
156
    @SuppressWarnings("unchecked")
157
    public void performFinish(IProgressMonitor monitor) throws CoreException,
158
            InterruptedException {
159
        try {
160
161
            monitor
162
                    .beginTask(
163
                            MTJUIMessages.NewMidletProjectWizardPageTwo_performFinish_monitor_taskname,
164
                            3);
165
            if (currProject == null) {
166
                updateProject(new SubProgressMonitor(monitor, 1));
167
            }
168
169
            configureJavaProject(new SubProgressMonitor(monitor, 2));
170
171
            if (!keepContent) {
172
                IJavaProject project = JavaCore.create(currProject);
173
                Map options = project.getOptions(false);
174
175
                // complete compliance options
176
                project.setOptions(options);
177
            }
178
179
        } finally {
180
            monitor.done();
181
            currProject = null;
182
            if (isAutobuild != null) {
183
                IWorkspaceDescription description = ResourcesPlugin
184
                        .getWorkspace().getDescription();
185
                description.setAutoBuilding(isAutobuild.booleanValue());
186
                MTJCore.getWorkspace().setDescription(description);
187
                isAutobuild = null;
188
            }
189
        }
190
    }
191
192
    /*
193
     * (non-Javadoc)
194
     * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
195
     */
196
    @Override
197
    public void setVisible(boolean visible) {
198
        boolean isShownFirstTime = visible && (currProject == null);
199
        if (visible) {
200
            if (isShownFirstTime) {
201
                // entering from the first page
202
                createProvisonalProject();
203
            }
204
        } else {
205
            if ((getContainer().getCurrentPage() == firstPage)
206
                    || (getContainer().getCurrentPage() == pageLibrary)) {
207
                // leaving back to previous pages
208
                removeProvisonalProject();
209
            }
210
        }
211
        super.setVisible(visible);
212
        if (isShownFirstTime) {
213
            setFocus();
214
        }
215
    }
216
217
    /**
218
     * Update the java configuration before making the page visible.
219
     */
220
    public void updateConfiguration() {
221
        String projectName = firstPage.getProjectName();
222
223
        currProject = MTJCore.getWorkspace().getRoot().getProject(
224
                projectName);
225
226
        IJavaProject javaProject = JavaCore.create(currProject);
227
        IPath projectPath = currProject.getFullPath();
228
229
        // Initialize the classpath entries using the source directories
230
        // and classpath container
231
        ArrayList<IClasspathEntry> entryList = new ArrayList<IClasspathEntry>();
232
        entryList.add(getSrcPathEntry(projectPath));
233
        addResourcesDirectoryIfRequested(entryList, currProject);
234
        IPath entryPath = new Path(JavaMEClasspathContainer.JAVAME_CONTAINER
235
                + "/" + firstPage.getSelectedDevice()); //$NON-NLS-1$
236
237
        entryList.add(JavaCore.newContainerEntry(entryPath));
238
239
        IClasspathEntry[] entries = entryList
240
                .toArray(new IClasspathEntry[entryList.size()]);
241
242
        init(javaProject, null, entries, false);
243
    }
244
245
    /**
246
     * Add a resources directory as a source path entry if the user preferences
247
     * requested.
248
     * 
249
     * @param entryList
250
     * @param project
251
     */
252
    private void addResourcesDirectoryIfRequested(
253
            List<IClasspathEntry> entryList, IProject project) {
254
        Preferences prefs = MTJCore.getMTJCore().getPluginPreferences();
255
256
        if (useSourceAndBinaryFolders()
257
                && prefs.getBoolean(IMTJCoreConstants.PREF_USE_RESOURCES_DIR)) {
258
            // Create the resources directory if it doesn't already exist
259
            String resDirName = prefs
260
                    .getString(IMTJCoreConstants.PREF_RESOURCES_DIR);
261
            IFolder resFolder = project.getFolder(resDirName);
262
263
            if (!resFolder.exists()) {
264
                try {
265
                    resFolder.create(true, true, new NullProgressMonitor());
266
                } catch (CoreException e) {
267
                    e.printStackTrace();
268
                }
269
            }
270
271
            // Add it as a source folder to the java project
272
            entryList.add(JavaCore.newSourceEntry(resFolder.getFullPath()));
273
        }
274
    }
275
276
    private IStatus changeToNewProject() {
277
        class UpdateRunnable implements IRunnableWithProgress {
278
            public IStatus infoStatus = Status.OK_STATUS;
279
280
            public void run(IProgressMonitor monitor)
281
                    throws InvocationTargetException, InterruptedException {
282
                try {
283
                    if (isAutobuild == null) {
284
                        IWorkspaceDescription description = ResourcesPlugin
285
                                .getWorkspace().getDescription();
286
                        isAutobuild = Boolean.valueOf(description
287
                                .isAutoBuilding());
288
                        description.setAutoBuilding(false);
289
                        MTJCore.getWorkspace().setDescription(
290
                                description);
291
                    }
292
                    infoStatus = updateProject(monitor);
293
                } catch (CoreException e) {
294
                    throw new InvocationTargetException(e);
295
                } catch (OperationCanceledException e) {
296
                    throw new InterruptedException();
297
                } finally {
298
                    monitor.done();
299
                }
300
            }
301
        }
302
303
        UpdateRunnable op = new UpdateRunnable();
304
        try {
305
            getContainer().run(true, false,
306
                    new WorkspaceModifyDelegatingOperation(op));
307
308
            return op.infoStatus;
309
        } catch (InvocationTargetException e) {
310
311
            final String title = MTJUIMessages.NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_title;
312
            final String message = MTJUIMessages.NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_message;
313
            ExceptionHandler.handle(e, getShell(), title, message);
314
315
        } catch (InterruptedException e) {
316
            // cancel pressed
317
        }
318
        return null;
319
    }
320
321
    /**
322
     * @param source
323
     * @param target
324
     * @param monitor
325
     * @throws IOException
326
     * @throws CoreException
327
     */
328
    private void copyFile(File source, IFileStore target,
329
            IProgressMonitor monitor) throws IOException, CoreException {
330
        FileInputStream is = new FileInputStream(source);
331
        OutputStream os = target.openOutputStream(EFS.NONE, monitor);
332
        copyFile(is, os);
333
    }
334
335
    /**
336
     * @param source
337
     * @param target
338
     * @throws IOException
339
     * @throws CoreException
340
     */
341
    private void copyFile(IFileStore source, File target) throws IOException,
342
            CoreException {
343
        InputStream is = source.openInputStream(EFS.NONE, null);
344
        FileOutputStream os = new FileOutputStream(target);
345
        copyFile(is, os);
346
    }
347
348
    /**
349
     * @param is
350
     * @param os
351
     * @throws IOException
352
     */
353
    private void copyFile(InputStream is, OutputStream os) throws IOException {
354
        try {
355
            byte[] buffer = new byte[8192];
356
            while (true) {
357
                int bytesRead = is.read(buffer);
358
                if (bytesRead == -1) {
359
                    break;
360
                }
361
362
                os.write(buffer, 0, bytesRead);
363
            }
364
        } finally {
365
            try {
366
                is.close();
367
            } finally {
368
                os.close();
369
            }
370
        }
371
    }
372
373
    /**
374
     * @param source
375
     * @param name
376
     * @return
377
     * @throws CoreException
378
     */
379
    private File createBackup(IFileStore source, String name)
380
            throws CoreException {
381
        try {
382
            File bak = File.createTempFile("eclipse-" + name, ".bak"); //$NON-NLS-1$//$NON-NLS-2$
383
            copyFile(source, bak);
384
            return bak;
385
        } catch (IOException e) {
386
            IStatus status = new Status(
387
                    IStatus.ERROR,
388
                    IMTJUIConstants.PLUGIN_ID,
389
                    IStatus.ERROR,
390
                    MTJUIMessages.NewMidletProjectWizardPageTwo_createBackup_error_1
391
                            + name
392
                            + MTJUIMessages.NewMidletProjectWizardPageTwo_createBackup_error_2,
393
                    e);
394
            throw new CoreException(status);
395
        }
396
    }
397
398
    private void deleteProjectFile(URI projectLocation) throws CoreException {
399
        IFileStore file = EFS.getStore(projectLocation);
400
        if (file.fetchInfo().exists()) {
401
            IFileStore projectFile = file.getChild(FILENAME_PROJECT);
402
            if (projectFile.fetchInfo().exists()) {
403
                projectFile.delete(EFS.NONE, null);
404
            }
405
        }
406
    }
407
408
    private final void doRemoveProject(IProgressMonitor monitor)
409
            throws InvocationTargetException {
410
        final boolean noProgressMonitor = (currProjectLocation == null); // inside
411
        // workspace
412
        if ((monitor == null) || noProgressMonitor) {
413
            monitor = new NullProgressMonitor();
414
        }
415
        monitor
416
                .beginTask(
417
                        MTJUIMessages.NewMidletProjectWizardPageTwo_doRemoveProject_taskname,
418
                        3);
419
        try {
420
            try {
421
                URI projLoc = currProject.getLocationURI();
422
423
                boolean removeContent = !keepContent
424
                        && currProject.isSynchronized(IResource.DEPTH_INFINITE);
425
                if ((!removeContent)
426
                        && (currProject.getProject().getFullPath().toFile()
427
                                .exists())) {
428
                    restoreExistingFolders(projLoc);
429
                }
430
                currProject.delete(removeContent, false,
431
                        new SubProgressMonitor(monitor, 2));
432
433
                MidletSuiteFactory.removeMidletSuiteProject(getJavaProject());
434
435
                restoreExistingFiles(projLoc,
436
                        new SubProgressMonitor(monitor, 1));
437
            } finally {
438
                IWorkspaceDescription description = ResourcesPlugin
439
                        .getWorkspace().getDescription();
440
                description.setAutoBuilding(isAutobuild.booleanValue());
441
                MTJCore.getWorkspace().setDescription(description);
442
                // isAutobuild must be set
443
                isAutobuild = null;
444
            }
445
        } catch (CoreException e) {
446
            throw new InvocationTargetException(e);
447
        } finally {
448
            monitor.done();
449
            currProject = null;
450
            keepContent = false;
451
        }
452
    }
453
454
    /**
455
     * Get the source path for the project taking into account the new project
456
     * preferences that the user has specified.
457
     * 
458
     * @param projectPath
459
     * @return
460
     */
461
    private IPath getSrcPath(IPath projectPath) {
462
        IPath srcPath = projectPath;
463
464
        if (useSourceAndBinaryFolders()) {
465
            IPreferenceStore store = PreferenceConstants.getPreferenceStore();
466
            String srcPathName = store
467
                    .getString(PreferenceConstants.SRCBIN_SRCNAME);
468
            srcPath = projectPath.append(srcPathName);
469
        }
470
471
        return srcPath;
472
    }
473
474
    /**
475
     * Return an IClasspathEntry for the source path.
476
     * 
477
     * @param projectPath
478
     * @return
479
     */
480
    private IClasspathEntry getSrcPathEntry(IPath projectPath) {
481
        IPath srcPath = getSrcPath(projectPath);
482
483
        // Set up exclusions for the verified and deployed directories
484
        // if the source and project directories are the same
485
        IPath[] exclusions = null;
486
        if (srcPath.equals(projectPath)) {
487
            exclusions = new IPath[3];
488
            exclusions[0] = new Path(MTJCore.getDeploymentDirectoryName() + "/"); //$NON-NLS-1$
489
            exclusions[1] = new Path(IMTJCoreConstants.TEMP_FOLDER_NAME + "/"); //$NON-NLS-1$
490
            exclusions[2] = new Path(PreprocessorBuilder.PROCESSED_DIRECTORY
491
                    + "/"); //$NON-NLS-1$
492
        } else {
493
            exclusions = new IPath[0];
494
        }
495
496
        return JavaCore.newSourceEntry(srcPath, exclusions);
497
    }
498
499
    /**
500
     * @param realLocation
501
     * @return
502
     * @throws CoreException
503
     */
504
    private boolean hasExistingContent(URI realLocation) throws CoreException {
505
        IFileStore file = EFS.getStore(realLocation);
506
        return file.fetchInfo().exists();
507
    }
508
509
    private void rememberExisitingFolders(URI projectLocation) {
510
        fOrginalFolders = new HashSet<IFileStore>();
511
512
        try {
513
            IFileStore[] children = EFS.getStore(projectLocation).childStores(
514
                    EFS.NONE, null);
515
            for (IFileStore child : children) {
516
                IFileInfo info = child.fetchInfo();
517
                if (info.isDirectory() && info.exists()
518
                        && !fOrginalFolders.contains(child.getName())) {
519
                    fOrginalFolders.add(child);
520
                }
521
            }
522
        } catch (CoreException e) {
523
            final String title = MTJUIMessages.NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_title;
524
            final String message = MTJUIMessages.NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_message;
525
            ExceptionHandler.handle(e, getShell(), title, message);
526
        }
527
    }
528
529
    private void rememberExistingFiles(URI projectLocation)
530
            throws CoreException {
531
        fDotProjectBackup = null;
532
        fDotClasspathBackup = null;
533
534
        IFileStore file = EFS.getStore(projectLocation);
535
        if (file.fetchInfo().exists()) {
536
            IFileStore projectFile = file.getChild(FILENAME_PROJECT);
537
            if (projectFile.fetchInfo().exists()) {
538
                fDotProjectBackup = createBackup(projectFile, "project-desc"); //$NON-NLS-1$ 
539
            }
540
            IFileStore classpathFile = file.getChild(FILENAME_CLASSPATH);
541
            if (classpathFile.fetchInfo().exists()) {
542
                fDotClasspathBackup = createBackup(classpathFile,
543
                        "classpath-desc"); //$NON-NLS-1$ 
544
            }
545
        }
546
    }
547
548
    private void restoreExistingFiles(URI projectLocation,
549
            IProgressMonitor monitor) throws CoreException {
550
        int ticks = ((fDotProjectBackup != null ? 1 : 0) + (fDotClasspathBackup != null ? 1
551
                : 0)) * 2;
552
        monitor.beginTask("", ticks); //$NON-NLS-1$
553
        try {
554
            IFileStore projectFile = EFS.getStore(projectLocation).getChild(
555
                    FILENAME_PROJECT);
556
            projectFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
557
            if (fDotProjectBackup != null) {
558
                copyFile(fDotProjectBackup, projectFile,
559
                        new SubProgressMonitor(monitor, 1));
560
            }
561
        } catch (IOException e) {
562
            IStatus status = new Status(
563
                    IStatus.ERROR,
564
                    IMTJUIConstants.PLUGIN_ID,
565
                    IStatus.ERROR,
566
                    MTJUIMessages.NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotproject,
567
                    e);
568
            throw new CoreException(status);
569
        }
570
        try {
571
            IFileStore classpathFile = EFS.getStore(projectLocation).getChild(
572
                    FILENAME_CLASSPATH);
573
            classpathFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
574
            if (fDotClasspathBackup != null) {
575
                copyFile(fDotClasspathBackup, classpathFile,
576
                        new SubProgressMonitor(monitor, 1));
577
            }
578
        } catch (IOException e) {
579
            IStatus status = new Status(
580
                    IStatus.ERROR,
581
                    IMTJUIConstants.PLUGIN_ID,
582
                    IStatus.ERROR,
583
                    MTJUIMessages.NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotclasspath,
584
                    e);
585
            throw new CoreException(status);
586
        }
587
    }
588
589
    private void restoreExistingFolders(URI projectLocation) {
590
        try {
591
            IFileStore[] children = EFS.getStore(projectLocation).childStores(
592
                    EFS.NONE, null);
593
            for (IFileStore child : children) {
594
                IFileInfo info = child.fetchInfo();
595
                if (info.isDirectory() && info.exists()
596
                        && !fOrginalFolders.contains(child)) {
597
                    child.delete(EFS.NONE, null);
598
                    fOrginalFolders.remove(child);
599
                }
600
            }
601
602
            for (IFileStore fileStore : fOrginalFolders) {
603
                IFileStore deleted = fileStore;
604
                deleted.mkdir(EFS.NONE, null);
605
            }
606
        } catch (CoreException e) {
607
            final String title = MTJUIMessages.NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_title;
608
            final String message = MTJUIMessages.NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_message;
609
            ExceptionHandler.handle(e, getShell(), title, message);
610
        }
611
    }
612
613
    /**
614
     * @param monitor
615
     * @return
616
     * @throws CoreException
617
     * @throws InterruptedException
618
     */
619
    private final IStatus updateProject(IProgressMonitor monitor)
620
            throws CoreException, InterruptedException {
621
        IStatus result = Status.OK_STATUS;
622
        if (monitor == null) {
623
            monitor = new NullProgressMonitor();
624
        }
625
        try {
626
            monitor
627
                    .beginTask(
628
                            MTJUIMessages.NewMidletProjectWizardPageTwo_updateProject_taskname,
629
                            7);
630
            if (monitor.isCanceled()) {
631
                throw new OperationCanceledException();
632
            }
633
634
            String projectName = firstPage.getProjectName();
635
636
            currProject = MTJCore.getWorkspace().getRoot().getProject(
637
                    projectName);
638
            currProjectLocation = firstPage.getProjectLocationURI();
639
640
            URI realLocation = getRealLocation(projectName, currProjectLocation);
641
            keepContent = hasExistingContent(realLocation);
642
643
            if (monitor.isCanceled()) {
644
                throw new OperationCanceledException();
645
            }
646
647
            if (keepContent) {
648
                rememberExistingFiles(realLocation);
649
                rememberExisitingFolders(realLocation);
650
            }
651
652
            if (monitor.isCanceled()) {
653
                throw new OperationCanceledException();
654
            }
655
656
            try {
657
658
                JavaCapabilityConfigurationPage.createProject(currProject,
659
                        firstPage.getProjectLocationURI(),
660
                        new SubProgressMonitor(monitor, 1));
661
662
                // Set the device into the project metadata to make
663
                // the java project creation happy.
664
                IDevice device = firstPage.getSelectedDevice();
665
                MTJRuntimeList configurations = firstPage.getConfigurations();
666
                // Make up Metadata and save it.
667
                IMetaData metadata = MTJCore.createMetaData(currProject,
668
                        ProjectType.MIDLET_SUITE);
669
                metadata.setMTJRuntimeList(configurations);
670
                try {
671
                    metadata.saveMetaData();
672
                } catch (CoreException e) {
673
                    throw new InvocationTargetException(e);
674
                }
675
676
                updateConfiguration();
677
678
                // Get the java nature
679
                try {
680
                    IRunnableWithProgress progress = super.getRunnable();
681
                    progress.run(monitor);
682
                } catch (Throwable e) {
683
                    throw new CoreException(new Status(
684
                            IResourceStatus.FAILED_READ_METADATA, "", e //$NON-NLS-1$
685
                                    .getMessage()));
686
                }
687
688
                // Get the J2ME nature and metadata set up
689
                String jadFileName = firstPage.getJadFileName();
690
691
                IJavaProject javaProject = super.getJavaProject();
692
693
                MidletSuiteFactory.MidletSuiteCreationRunnable runnable = MidletSuiteFactory
694
                        .getMidletSuiteCreationRunnable(currProject,
695
                                javaProject, (IMIDPDevice) device, jadFileName);
696
697
                runnable.setPreprocessingEnable(firstPage
698
                        .isPreprocessingEnabled());
699
700
                runnable.run(monitor);
701
702
            } catch (CoreException e) {
703
                if (e.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) {
704
                    result = new Status(
705
                            IStatus.INFO,
706
                            IMTJUIConstants.PLUGIN_ID,
707
                            MTJUIMessages.NewMidletProjectWizardPageTwo_updateProject_fail_read_metadata);
708
709
                    deleteProjectFile(realLocation);
710
                    if (currProject.exists()) {
711
                        currProject.delete(true, null);
712
                    }
713
714
                    createProject(currProject, currProjectLocation, null);
715
                } else {
716
                    throw e;
717
                }
718
            } catch (Throwable e) {
719
                throw new CoreException(Status.CANCEL_STATUS);
720
            }
721
722
            if (monitor.isCanceled()) {
723
                throw new OperationCanceledException();
724
            }
725
726
            initializeBuildPath(JavaCore.create(currProject),
727
                    new SubProgressMonitor(monitor, 2));
728
729
            configureJavaProject(new SubProgressMonitor(monitor, 3));
730
            // create the Java project to allow the use of the new source folder
731
            // page
732
        } catch (Exception e) {
733
            throw new CoreException(Status.CANCEL_STATUS);
734
        } finally {
735
            monitor.done();
736
        }
737
738
        return result;
739
    }
740
741
    /**
742
     * Return a boolean indicating whether there will be separate source and
743
     * binary folders in the project.
744
     * 
745
     * @return
746
     */
747
    private boolean useSourceAndBinaryFolders() {
748
        IPreferenceStore store = PreferenceConstants.getPreferenceStore();
749
        return store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
750
    }
751
752
    /**
753
     * Creates the provisional project on which the wizard is working on. The
754
     * provisional project is typically created when the page is entered the
755
     * first time. The early project creation is required to configure linked
756
     * folders.
757
     * 
758
     * @return the provisional project
759
     */
760
    protected IProject createProvisonalProject() {
761
        IStatus status = changeToNewProject();
762
        if ((status != null) && !status.isOK()) {
763
            ErrorDialog.openError(getShell(), "createProvisonalProject", null, //$NON-NLS-1$
764
                    status);
765
        }
766
        return currProject;
767
    }
768
769
    /**
770
     * Evaluates the new build path and output folder according to the settings
771
     * on the first page. The resulting build path is set by calling
772
     * {@link #init(IJavaProject, IPath, IClasspathEntry[], boolean)}. Clients
773
     * can override this method.
774
     * 
775
     * @param javaProject the new project which is already created when this
776
     *            method is called.
777
     * @param monitor the progress monitor
778
     * @throws CoreException thrown when initializing the build path failed
779
     */
780
    protected void initializeBuildPath(IJavaProject javaProject,
781
            IProgressMonitor monitor) throws CoreException {
782
        if (monitor == null) {
783
            monitor = new NullProgressMonitor();
784
        }
785
        monitor
786
                .beginTask(
787
                        MTJUIMessages.NewMidletProjectWizardPageTwo_updateProject_monitor_buildpath_name,
788
                        2);
789
790
        try {
791
            IClasspathEntry[] entries = null;
792
            IProject project = javaProject.getProject();
793
794
            List<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
795
            IWorkspaceRoot root = project.getWorkspace().getRoot();
796
797
            IClasspathEntry sourceClasspathEntry = getSrcPathEntry(project
798
                    .getFullPath());
799
800
            if (sourceClasspathEntry.getPath() != project.getFullPath()) {
801
802
                IFolder folder = root.getFolder(sourceClasspathEntry.getPath());
803
804
                if (!folder.exists()) {
805
                    folder.create(true, true,
806
                            new SubProgressMonitor(monitor, 1));
807
                }
808
            }
809
            cpEntries.add(sourceClasspathEntry);
810
            addResourcesDirectoryIfRequested(cpEntries, project);
811
812
            IPath entryPath = new Path(
813
                    JavaMEClasspathContainer.JAVAME_CONTAINER + "/" //$NON-NLS-1$
814
                            + firstPage.getSelectedDevice());
815
            cpEntries.add(JavaCore.newContainerEntry(entryPath));
816
817
            if (pageLibrary != null) {
818
                List<IPath> list = pageLibrary.getSelectedLibraries();
819
820
                for (IPath path : list) {
821
                    cpEntries.add(JavaCore.newContainerEntry(path, true));
822
                }
823
            }
824
825
            entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
826
827
            if (monitor.isCanceled()) {
828
                throw new OperationCanceledException();
829
            }
830
831
            init(javaProject, getOutputLocation(), entries, true);
832
        } finally {
833
            monitor.done();
834
        }
835
    }
836
837
    /**
838
     * Removes the provisional project. The provisional project is typically
839
     * removed when the user cancels the wizard or goes back to the first page.
840
     */
841
    protected void removeProvisonalProject() {
842
        if (!currProject.exists()) {
843
            currProject = null;
844
            return;
845
        }
846
847
        IRunnableWithProgress op = new IRunnableWithProgress() {
848
            public void run(IProgressMonitor monitor)
849
                    throws InvocationTargetException, InterruptedException {
850
                doRemoveProject(monitor);
851
            }
852
        };
853
854
        try {
855
            getContainer().run(true, true,
856
                    new WorkspaceModifyDelegatingOperation(op));
857
        } catch (InvocationTargetException e) {
858
859
            final String title = MTJUIMessages.NewMidletProjectWizardPageTwo_updateProject_errordialog_title;
860
            final String message = MTJUIMessages.NewMidletProjectWizardPageTwo_updateProject_errordialog_message;
861
            ExceptionHandler.handle(e, getShell(), title, message);
862
863
        } catch (InterruptedException e) {
864
            // cancel pressed
865
        }
866
    }
867
868
    /*
869
     * (non-Javadoc)
870
     * @see
871
     * org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage#useNewSourcePage
872
     * ()
873
     */
874
    @Override
875
    protected final boolean useNewSourcePage() {
876
        return true;
877
    }
878
}
(-)src/org/eclipse/mtj/internal/ui/wizards/projects/NewMidletProjectWizard.java (-16 / +25 lines)
Lines 11-16 Link Here
11
 *     Diego Sandin (Motorola) - Added library selection page
11
 *     Diego Sandin (Motorola) - Added library selection page
12
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
12
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
13
 *     David Marques (Motorola) - Refactoring build.properties
13
 *     David Marques (Motorola) - Refactoring build.properties
14
 *     Fernando Rocha (Motorola)- Add a page for project properties [Bug 261873]
14
 */
15
 */
15
package org.eclipse.mtj.internal.ui.wizards.projects;
16
package org.eclipse.mtj.internal.ui.wizards.projects;
16
17
Lines 54-61 Link Here
54
    private IConfigurationElement configElement;
55
    private IConfigurationElement configElement;
55
56
56
    private NewMidletProjectWizardPageOne firstPage;
57
    private NewMidletProjectWizardPageOne firstPage;
58
    private NewMidletProjectWizardPageProperties propertiesPage;
57
    private NewMidletProjectWizardPageLibrary libraryPage;
59
    private NewMidletProjectWizardPageLibrary libraryPage;
58
    private NewMidletProjectWizardPageTwo secondPage;
60
    private NewMidletProjectWizardPageJavaSettings javaSettingsPage;
59
61
60
    private IWorkbench workbench;
62
    private IWorkbench workbench;
61
63
Lines 63-69 Link Here
63
     * Construct a new MIDLet project wizard.
65
     * Construct a new MIDLet project wizard.
64
     */
66
     */
65
    public NewMidletProjectWizard() {
67
    public NewMidletProjectWizard() {
66
        this(null, null, null);
68
        this(null, null, null, null);
67
    }
69
    }
68
70
69
    /**
71
    /**
Lines 71-80 Link Here
71
     * 
73
     * 
72
     * @param pageOne the first wizard page
74
     * @param pageOne the first wizard page
73
     * @param pageTwo the second wizard page
75
     * @param pageTwo the second wizard page
76
     * @param pageThree the third wizard page
74
     * @param libraryPage the library wizard page
77
     * @param libraryPage the library wizard page
75
     */
78
     */
76
    public NewMidletProjectWizard(NewMidletProjectWizardPageOne pageOne,
79
    public NewMidletProjectWizard(NewMidletProjectWizardPageOne pageOne,
77
            NewMidletProjectWizardPageTwo pageTwo,
80
            NewMidletProjectWizardPageProperties pageTwo,
81
            NewMidletProjectWizardPageJavaSettings pageThree,
78
            NewMidletProjectWizardPageLibrary libraryPage) {
82
            NewMidletProjectWizardPageLibrary libraryPage) {
79
83
80
        ImageDescriptor descriptor = MTJUIPluginImages.DESC_NEW_PROJECT;
84
        ImageDescriptor descriptor = MTJUIPluginImages.DESC_NEW_PROJECT;
Lines 82-88 Link Here
82
        setWindowTitle(MTJUIMessages.NewMidletProjectWizard_wizard_title);
86
        setWindowTitle(MTJUIMessages.NewMidletProjectWizard_wizard_title);
83
87
84
        this.firstPage = pageOne;
88
        this.firstPage = pageOne;
85
        this.secondPage = pageTwo;
89
        this.propertiesPage = pageTwo;
90
        this.javaSettingsPage = pageThree;
86
        this.libraryPage = libraryPage;
91
        this.libraryPage = libraryPage;
87
    }
92
    }
88
93
Lines 96-101 Link Here
96
            firstPage = new NewMidletProjectWizardPageOne();
101
            firstPage = new NewMidletProjectWizardPageOne();
97
        }
102
        }
98
        addPage(firstPage);
103
        addPage(firstPage);
104
        
105
        if(propertiesPage == null) {
106
        	propertiesPage = new NewMidletProjectWizardPageProperties(firstPage);
107
        }
108
        addPage(propertiesPage);
99
109
100
        if (libraryPage == null) {
110
        if (libraryPage == null) {
101
            libraryPage = new NewMidletProjectWizardPageLibrary();
111
            libraryPage = new NewMidletProjectWizardPageLibrary();
Lines 104-115 Link Here
104
        if (libraryPage.isPageDisplayable()) {
114
        if (libraryPage.isPageDisplayable()) {
105
            addPage(libraryPage);
115
            addPage(libraryPage);
106
        }
116
        }
107
117
        
108
        if (secondPage == null) {
118
        if (javaSettingsPage == null) {
109
            secondPage = new NewMidletProjectWizardPageTwo(firstPage,
119
            javaSettingsPage = new NewMidletProjectWizardPageJavaSettings(firstPage, 
110
                    libraryPage);
120
            		propertiesPage, libraryPage);
111
        }
121
        }
112
        addPage(secondPage);
122
        addPage(javaSettingsPage);
113
123
114
        firstPage.init(getSelection(), getActivePart());
124
        firstPage.init(getSelection(), getActivePart());
115
    }
125
    }
Lines 130-136 Link Here
130
     */
140
     */
131
    @Override
141
    @Override
132
    public IJavaElement getCreatedElement() {
142
    public IJavaElement getCreatedElement() {
133
        return secondPage.getJavaProject();
143
        return javaSettingsPage.getJavaProject();
134
    }
144
    }
135
145
136
    /* (non-Javadoc)
146
    /* (non-Javadoc)
Lines 148-154 Link Here
148
     */
158
     */
149
    @Override
159
    @Override
150
    public boolean performCancel() {
160
    public boolean performCancel() {
151
        secondPage.performCancel();
161
        javaSettingsPage.performCancel();
152
        return super.performCancel();
162
        return super.performCancel();
153
    }
163
    }
154
164
Lines 166-172 Link Here
166
            /* Open the Application Descriptor file */
176
            /* Open the Application Descriptor file */
167
            try {
177
            try {
168
                IMidletSuiteProject midletSuiteProject = MidletSuiteFactory
178
                IMidletSuiteProject midletSuiteProject = MidletSuiteFactory
169
                        .getMidletSuiteProject(secondPage.getJavaProject());
179
                        .getMidletSuiteProject(javaSettingsPage.getJavaProject());
170
180
171
                IFile jadfile = midletSuiteProject
181
                IFile jadfile = midletSuiteProject
172
                        .getApplicationDescriptorFile();
182
                        .getApplicationDescriptorFile();
Lines 178-185 Link Here
178
                }
188
                }
179
189
180
                MTJBuildProperties buildProperties = MTJBuildProperties
190
                MTJBuildProperties buildProperties = MTJBuildProperties
181
						.getBuildProperties(midletSuiteProject);
191
                        .getBuildProperties(midletSuiteProject);
182
				buildProperties.store();
192
                buildProperties.store();
183
            } catch (Throwable e) {
193
            } catch (Throwable e) {
184
                MTJLogger
194
                MTJLogger
185
                        .log(
195
                        .log(
Lines 199-205 Link Here
199
            String propertyName, Object data) {
209
            String propertyName, Object data) {
200
        configElement = cfig;
210
        configElement = cfig;
201
    }
211
    }
202
203
    private IWorkbenchPart getActivePart() {
212
    private IWorkbenchPart getActivePart() {
204
        IWorkbenchWindow activeWindow = getWorkbench()
213
        IWorkbenchWindow activeWindow = getWorkbench()
205
                .getActiveWorkbenchWindow();
214
                .getActiveWorkbenchWindow();
Lines 221-227 Link Here
221
    @Override
230
    @Override
222
    protected void finishPage(IProgressMonitor monitor)
231
    protected void finishPage(IProgressMonitor monitor)
223
            throws InterruptedException, CoreException {
232
            throws InterruptedException, CoreException {
224
        secondPage.performFinish(monitor); // use the full progress monitor
233
        javaSettingsPage.performFinish(monitor); // use the full progress monitor
225
    }
234
    }
226
235
227
    @Override
236
    @Override
(-)src/org/eclipse/mtj/internal/ui/wizards/projects/NewMidletProjectWizardPageProperties.java (+470 lines)
Line 0 Link Here
1
package org.eclipse.mtj.internal.ui.wizards.projects;
2
3
import java.util.HashMap;
4
import java.util.Map;
5
import java.util.Observable;
6
import java.util.Observer;
7
import java.util.regex.Matcher;
8
import java.util.regex.Pattern;
9
10
import org.eclipse.jface.dialogs.IDialogConstants;
11
import org.eclipse.jface.wizard.WizardPage;
12
import org.eclipse.mtj.core.sdk.device.IAPI;
13
import org.eclipse.mtj.internal.core.sdk.device.midp.Configuration;
14
import org.eclipse.mtj.internal.core.sdk.device.midp.Profile;
15
import org.eclipse.mtj.internal.ui.MTJUIMessages;
16
import org.eclipse.mtj.internal.ui.wizards.dialogfields.ComboDialogField;
17
import org.eclipse.mtj.internal.ui.wizards.dialogfields.DialogField;
18
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IDialogFieldListener;
19
import org.eclipse.mtj.internal.ui.wizards.dialogfields.LayoutUtil;
20
import org.eclipse.mtj.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
21
import org.eclipse.mtj.internal.ui.wizards.dialogfields.StringDialogField;
22
import org.eclipse.osgi.util.NLS;
23
import org.eclipse.swt.SWT;
24
import org.eclipse.swt.custom.ScrolledComposite;
25
import org.eclipse.swt.layout.GridData;
26
import org.eclipse.swt.layout.GridLayout;
27
import org.eclipse.swt.widgets.Composite;
28
import org.eclipse.swt.widgets.Control;
29
import org.eclipse.swt.widgets.Group;
30
31
public class NewMidletProjectWizardPageProperties extends WizardPage {
32
33
    private final class PropertiesGroup extends Observable implements
34
            IDialogFieldListener, Observer {
35
36
        private StringDialogField midletName;
37
        private StringDialogField midletVendor;
38
        private StringDialogField midletVersion;
39
        private ComboDialogField meConfiguration;
40
        private ComboDialogField meProfile;
41
        private Map<String, IAPI> configurations;
42
        private Map<String, IAPI> profiles;
43
44
        public PropertiesGroup() {
45
            configurations = new HashMap<String, IAPI>();
46
            profiles = new HashMap<String, IAPI>();
47
48
            midletName = new StringDialogField();
49
            midletName
50
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletName);
51
            midletName.setDialogFieldListener(this);
52
53
            midletVendor = new StringDialogField();
54
            midletVendor
55
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletVendor);
56
            midletVendor.setDialogFieldListener(this);
57
58
            midletVersion = new StringDialogField();
59
            midletVersion
60
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletVersion);
61
            midletVersion.setDialogFieldListener(this);
62
63
            IAPI[] meConfigurations = Configuration.values();
64
            String[] configurationNames = new String[meConfigurations.length];
65
            String defaultConfiguration = "";
66
            for (int i = 0; i < meConfigurations.length; i++) {
67
                configurationNames[i] = meConfigurations[i].getName();
68
                if (meConfigurations[i].toString().equals(
69
                        MTJUIMessages.MeConfigurationVersion)) {
70
                    defaultConfiguration = meConfigurations[i].getName();
71
                }
72
                configurations.put(configurationNames[i], meConfigurations[i]);
73
            }
74
75
            meConfiguration = new ComboDialogField(SWT.READ_ONLY);
76
            meConfiguration
77
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_meConfiguration);
78
            meConfiguration.setDialogFieldListener(this);
79
            meConfiguration.setItems(configurationNames);
80
            meConfiguration.setTextWithoutUpdate(defaultConfiguration);
81
82
            IAPI[] meProfiles = Profile.values();
83
            String[] profileNames = new String[meProfiles.length];
84
            String defaultProfile = "";
85
            for (int i = 0; i < meProfiles.length; i++) {
86
                profileNames[i] = meProfiles[i].getName();
87
                if (meProfiles[i].toString().equals(
88
                        MTJUIMessages.MeProfileVersion)) {
89
                    defaultProfile = meProfiles[i].getName();
90
                }
91
92
                profiles.put(profileNames[i], meProfiles[i]);
93
            }
94
95
            meProfile = new ComboDialogField(SWT.READ_ONLY);
96
            meProfile
97
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_meProfile);
98
            meProfile.setDialogFieldListener(this);
99
            meProfile.setItems(profileNames);
100
            meProfile.setTextWithoutUpdate(defaultProfile);
101
        }
102
103
        public Control createControl(Composite parent) {
104
            final int numColumns = 2;
105
106
            final Group group = new Group(parent, SWT.NONE);
107
            group.setLayout(initGridLayout(new GridLayout(numColumns, false),
108
                    true));
109
            group
110
                    .setText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_contents);
111
112
            midletName.doFillIntoGrid(group, numColumns);
113
            LayoutUtil.setHorizontalGrabbing(midletName.getTextControl(null));
114
            midletVendor.doFillIntoGrid(group, numColumns);
115
            LayoutUtil.setHorizontalGrabbing(midletVendor.getTextControl(null));
116
            midletVersion.doFillIntoGrid(group, numColumns);
117
            LayoutUtil
118
                    .setHorizontalGrabbing(midletVersion.getTextControl(null));
119
            meConfiguration.doFillIntoGrid(group, numColumns);
120
            LayoutUtil.setHorizontalGrabbing(meConfiguration
121
                    .getComboControl(null));
122
            meProfile.doFillIntoGrid(group, numColumns);
123
            LayoutUtil.setHorizontalGrabbing(meProfile.getComboControl(null));
124
125
            initValues();
126
127
            return group;
128
        }
129
130
        private void initValues() {
131
            midletName.setText(pageOne.getProjectName()
132
                    + MTJUIMessages.MidletDefaultNameEnd);
133
            midletVendor.setText(MTJUIMessages.MidletDefaultVendor);
134
            midletVersion.setText(MTJUIMessages.MidletInitialVersion_1_0_0);
135
        }
136
137
        public void dialogFieldChanged(DialogField field) {
138
            fireEvent();
139
        }
140
141
        protected void fireEvent() {
142
            setChanged();
143
            notifyObservers();
144
        }
145
146
        public String getMIDletName() {
147
            return midletName.getText();
148
        }
149
150
        public String getMIDletVendor() {
151
            return midletVendor.getText();
152
        }
153
154
        public String getMIDletVersion() {
155
            return midletVersion.getText();
156
        }
157
158
        public String getMeConfiguration() {
159
            return configurations.get(meConfiguration.getText()).toString();
160
        }
161
162
        public String getMeProfile() {
163
            return profiles.get(meProfile.getText()).toString();
164
        }
165
166
        public void update(Observable o, Object arg) {
167
            String midlet = midletName.getText();
168
            String projectName = pageOne.getProjectName();
169
            if (midlet.startsWith(projectName.substring(0,
170
                    projectName.length() - 1))
171
                    || midlet.equals(MTJUIMessages.MidletDefaultNameEnd)) {
172
                midletName.setText(projectName
173
                        + MTJUIMessages.MidletDefaultNameEnd);
174
            }
175
        }
176
177
    }
178
179
    private final class OptionsGroup extends Observable implements
180
            IDialogFieldListener {
181
182
        private SelectionButtonDialogField enablePreprocessing;
183
        private SelectionButtonDialogField enableLocalization;
184
        private StringDialogField propertiesFolder;
185
        private StringDialogField packageField;
186
        private SelectionButtonDialogField enableJMUnit;
187
188
        public OptionsGroup() {
189
            enablePreprocessing = new SelectionButtonDialogField(SWT.CHECK);
190
            enablePreprocessing
191
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_enablePreprocessing);
192
            enablePreprocessing.setDialogFieldListener(this);
193
194
            enableLocalization = new SelectionButtonDialogField(SWT.CHECK);
195
            enableLocalization
196
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_enableLocalization);
197
            enableLocalization.setDialogFieldListener(this);
198
199
            propertiesFolder = new StringDialogField();
200
            propertiesFolder
201
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_propertiesFolder);
202
            propertiesFolder.setDialogFieldListener(this);
203
            propertiesFolder.setTextWithoutUpdate("res");
204
            propertiesFolder.setEnabled(false);
205
206
            packageField = new StringDialogField();
207
            packageField
208
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_package);
209
            packageField.setDialogFieldListener(this);
210
211
            enableJMUnit = new SelectionButtonDialogField(SWT.CHECK);
212
            enableJMUnit
213
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_enableJMUnit);
214
            enableJMUnit.setDialogFieldListener(this);
215
216
            enablePreprocessing.setSelection(false);
217
            enableLocalization.setSelection(false);
218
            enableLocalization.attachDialogField(propertiesFolder);
219
            enableLocalization
220
                    .attachDialogFields(new DialogField[] { packageField });
221
        }
222
223
        public Control createControl(Composite parent) {
224
            final int numColumns = 2;
225
226
            final Group group = new Group(parent, SWT.NONE);
227
            group.setLayout(initGridLayout(new GridLayout(numColumns, false),
228
                    true));
229
            group
230
                    .setText(MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_contents);
231
232
            enablePreprocessing.doFillIntoGrid(group, numColumns);
233
            enableLocalization.doFillIntoGrid(group, numColumns);
234
            propertiesFolder.doFillIntoGrid(group, numColumns);
235
            LayoutUtil.setHorizontalGrabbing(propertiesFolder
236
                    .getTextControl(null));
237
            packageField.doFillIntoGrid(group, numColumns);
238
            LayoutUtil.setHorizontalGrabbing(packageField.getTextControl(null));
239
            enableJMUnit.doFillIntoGrid(group, numColumns);
240
241
            return group;
242
        }
243
244
        public void dialogFieldChanged(DialogField field) {
245
            fireEvent();
246
        }
247
248
        protected void fireEvent() {
249
            setChanged();
250
            notifyObservers();
251
        }
252
253
        public boolean isPreprocessingEnable() {
254
            return enablePreprocessing.isSelected();
255
        }
256
257
        public boolean isLocalizationEnable() {
258
            return enableLocalization.isSelected();
259
        }
260
261
        public String getPropertiesFolder() {
262
            return propertiesFolder.getText();
263
        }
264
265
        public String getPackage() {
266
            return packageField.getText();
267
        }
268
269
        public boolean isJMUnitEnable() {
270
            return enableJMUnit.isSelected();
271
        }
272
273
    }
274
275
    private final class Validator implements Observer {
276
277
        private Pattern packagePattern = Pattern
278
                .compile("([a-zA-Z_]\\w*)(\\.[a-zA-Z_]\\w*)*");
279
        private Pattern correctPattern = Pattern
280
                .compile("([a-z_]\\w*)(\\.[a-z_]\\w*)*");
281
282
        public void update(Observable o, Object arg) {
283
            if (getMIDletName().equals("")) {
284
                setErrorMessage(NLS
285
                        .bind(
286
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_fieldEmpty,
287
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletName));
288
                setMessage(null);
289
                setPageComplete(false);
290
                return;
291
            }
292
            if (getMIDletVendor().equals("")) {
293
                setErrorMessage(NLS
294
                        .bind(
295
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_fieldEmpty,
296
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletVendor));
297
                setMessage(null);
298
                setPageComplete(false);
299
                return;
300
            }
301
            if (getMIDletVersion().equals("")) {
302
                setErrorMessage(NLS
303
                        .bind(
304
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_fieldEmpty,
305
                                MTJUIMessages.NewMidletProjectWizardPageTwo_propertiesGroup_midletVersion));
306
                setMessage(null);
307
                setPageComplete(false);
308
                return;
309
            }
310
311
            if (isLocalizationEnabled()) {
312
                String packageName = getPackageName();
313
                if (packageName.equals("")) {
314
                    setErrorMessage(null);
315
                    setMessage(
316
                            MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_packageEmpty,
317
                            WizardPage.WARNING);
318
                    setPageComplete(true);
319
                    return;
320
                }
321
                Matcher packageMatcher = packagePattern.matcher(packageName);
322
                if (packageMatcher.matches()) {
323
                    Matcher correctMatcher = correctPattern
324
                            .matcher(packageName);
325
                    // Correct package
326
                    if (correctMatcher.matches()) {
327
                        setErrorMessage(null);
328
                        setMessage(null);
329
                        setPageComplete(true);
330
                        return;
331
                    }
332
                    // Upper case package
333
                    else {
334
                        setErrorMessage(null);
335
                        setMessage(
336
                                MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_packageUpperCase,
337
                                WizardPage.WARNING);
338
                        setPageComplete(true);
339
                        return;
340
                    }
341
                }
342
                // Error package
343
                else {
344
                    setMessage(null);
345
                    setErrorMessage(NLS
346
                            .bind(
347
                                    MTJUIMessages.NewMidletProjectWizardPageTwo_optionsGroup_packageError,
348
                                    packageName));
349
                    setPageComplete(false);
350
                    return;
351
                }
352
            }
353
            setErrorMessage(null);
354
            setMessage(null);
355
            setPageComplete(true);
356
        }
357
    }
358
359
    private static final String PAGE_NAME = "NewJavaProjectWizardPageTwo"; //$NON-NLS-1$
360
    private NewMidletProjectWizardPageOne pageOne;
361
    private PropertiesGroup propertiesGroup;
362
    private OptionsGroup optionsGroup;
363
    private Validator validator;
364
365
    public NewMidletProjectWizardPageProperties(
366
            NewMidletProjectWizardPageOne firstPage) {
367
        super(PAGE_NAME);
368
        setTitle(MTJUIMessages.NewMidletProjectWizardPageTwo_title);
369
        setDescription(MTJUIMessages.NewMidletProjectWizardPageTwo_description);
370
371
        this.pageOne = firstPage;
372
        this.validator = new Validator();
373
374
        this.propertiesGroup = new PropertiesGroup();
375
        this.optionsGroup = new OptionsGroup();
376
377
        this.pageOne.getProjectNameGroup().addObserver(propertiesGroup);
378
        this.propertiesGroup.addObserver(validator);
379
        this.optionsGroup.addObserver(validator);
380
    }
381
382
    public void createControl(Composite parent) {
383
        initializeDialogUnits(parent);
384
385
        ScrolledComposite scrolledComposite = new ScrolledComposite(parent,
386
                SWT.V_SCROLL | SWT.H_SCROLL);
387
        scrolledComposite.setExpandHorizontal(true);
388
        scrolledComposite.setExpandVertical(true);
389
        scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
390
                true));
391
392
        final Composite composite = new Composite(scrolledComposite, SWT.NONE);
393
        composite.setFont(parent.getFont());
394
        composite.setLayout(initGridLayout(new GridLayout(), true));
395
396
        // create UI elements
397
        Control nameControl = createPropertiesControl(composite);
398
        nameControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
399
400
        Control optionsControl = createOptionsControl(composite);
401
        optionsControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
402
403
        scrolledComposite.setContent(composite);
404
        scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT,
405
                SWT.DEFAULT));
406
        setControl(scrolledComposite);
407
    }
408
409
    private Control createOptionsControl(Composite parent) {
410
        return optionsGroup.createControl(parent);
411
    }
412
413
    protected Control createPropertiesControl(Composite parent) {
414
        return propertiesGroup.createControl(parent);
415
    }
416
417
    public boolean isPreprocessingEnabled() {
418
        return optionsGroup.isPreprocessingEnable();
419
    }
420
421
    public boolean isLocalizationEnabled() {
422
        return optionsGroup.isLocalizationEnable();
423
    }
424
425
    public boolean isJMUnitEnabled() {
426
        return optionsGroup.isJMUnitEnable();
427
    }
428
429
    public String getMIDletName() {
430
        return propertiesGroup.getMIDletName();
431
    }
432
433
    public String getMIDletVendor() {
434
        return propertiesGroup.getMIDletVendor();
435
    }
436
437
    public String getMIDletVersion() {
438
        return propertiesGroup.getMIDletVersion();
439
    }
440
441
    public String getMeConfiguration() {
442
        return propertiesGroup.getMeConfiguration();
443
    }
444
445
    public String getMeProfile() {
446
        return propertiesGroup.getMeProfile();
447
    }
448
449
    public String getPropertiesFolderName() {
450
        return optionsGroup.getPropertiesFolder();
451
    }
452
453
    public String getPackageName() {
454
        return optionsGroup.getPackage();
455
    }
456
457
    private GridLayout initGridLayout(GridLayout layout, boolean margins) {
458
        layout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
459
        layout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
460
        if (margins) {
461
            layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
462
            layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
463
        } else {
464
            layout.marginWidth = 0;
465
            layout.marginHeight = 0;
466
        }
467
        return layout;
468
    }
469
470
}
(-)src/org/eclipse/mtj/internal/ui/wizards/projects/NewMidletProjectWizardPageOne.java (-58 / +166 lines)
Lines 12-17 Link Here
12
 *                               management section, for multi-configs support. 
12
 *                               management section, for multi-configs support. 
13
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
13
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
14
 *     Fernando Rocha (Motorola) - Add the scroll bar in the page [Bug 273646]
14
 *     Fernando Rocha (Motorola) - Add the scroll bar in the page [Bug 273646]
15
 *     Fernando Rocha (Motorola) - Add the WorkingSet preference [Bug 261873]
15
 */
16
 */
16
package org.eclipse.mtj.internal.ui.wizards.projects;
17
package org.eclipse.mtj.internal.ui.wizards.projects;
17
18
Lines 18-23 Link Here
18
import java.io.File;
19
import java.io.File;
19
import java.io.IOException;
20
import java.io.IOException;
20
import java.net.URI;
21
import java.net.URI;
22
import java.util.ArrayList;
23
import java.util.Arrays;
24
import java.util.List;
21
import java.util.Observable;
25
import java.util.Observable;
22
import java.util.Observer;
26
import java.util.Observer;
23
27
Lines 37-42 Link Here
37
import org.eclipse.jface.dialogs.Dialog;
41
import org.eclipse.jface.dialogs.Dialog;
38
import org.eclipse.jface.dialogs.IDialogConstants;
42
import org.eclipse.jface.dialogs.IDialogConstants;
39
import org.eclipse.jface.viewers.IStructuredSelection;
43
import org.eclipse.jface.viewers.IStructuredSelection;
44
import org.eclipse.jface.window.Window;
40
import org.eclipse.jface.wizard.WizardPage;
45
import org.eclipse.jface.wizard.WizardPage;
41
import org.eclipse.mtj.core.MTJCore;
46
import org.eclipse.mtj.core.MTJCore;
42
import org.eclipse.mtj.core.project.runtime.MTJRuntime;
47
import org.eclipse.mtj.core.project.runtime.MTJRuntime;
Lines 52-58 Link Here
52
import org.eclipse.mtj.internal.ui.MTJUIMessages;
57
import org.eclipse.mtj.internal.ui.MTJUIMessages;
53
import org.eclipse.mtj.internal.ui.MTJUIPlugin;
58
import org.eclipse.mtj.internal.ui.MTJUIPlugin;
54
import org.eclipse.mtj.internal.ui.configurations.ConfigManageComponent;
59
import org.eclipse.mtj.internal.ui.configurations.ConfigManageComponent;
60
import org.eclipse.mtj.internal.ui.wizards.dialogfields.ComboButtonDialogField;
55
import org.eclipse.mtj.internal.ui.wizards.dialogfields.DialogField;
61
import org.eclipse.mtj.internal.ui.wizards.dialogfields.DialogField;
62
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IComboButtonAdapter;
56
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IDialogFieldListener;
63
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IDialogFieldListener;
57
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IStringButtonAdapter;
64
import org.eclipse.mtj.internal.ui.wizards.dialogfields.IStringButtonAdapter;
58
import org.eclipse.mtj.internal.ui.wizards.dialogfields.LayoutUtil;
65
import org.eclipse.mtj.internal.ui.wizards.dialogfields.LayoutUtil;
Lines 61-71 Link Here
61
import org.eclipse.mtj.internal.ui.wizards.dialogfields.StringDialogField;
68
import org.eclipse.mtj.internal.ui.wizards.dialogfields.StringDialogField;
62
import org.eclipse.swt.SWT;
69
import org.eclipse.swt.SWT;
63
import org.eclipse.swt.custom.ScrolledComposite;
70
import org.eclipse.swt.custom.ScrolledComposite;
64
import org.eclipse.swt.events.SelectionAdapter;
65
import org.eclipse.swt.events.SelectionEvent;
66
import org.eclipse.swt.layout.GridData;
71
import org.eclipse.swt.layout.GridData;
67
import org.eclipse.swt.layout.GridLayout;
72
import org.eclipse.swt.layout.GridLayout;
68
import org.eclipse.swt.widgets.Button;
69
import org.eclipse.swt.widgets.Composite;
73
import org.eclipse.swt.widgets.Composite;
70
import org.eclipse.swt.widgets.Control;
74
import org.eclipse.swt.widgets.Control;
71
import org.eclipse.swt.widgets.DirectoryDialog;
75
import org.eclipse.swt.widgets.DirectoryDialog;
Lines 71-77 Link Here
71
import org.eclipse.swt.widgets.DirectoryDialog;
75
import org.eclipse.swt.widgets.DirectoryDialog;
72
import org.eclipse.swt.widgets.Group;
76
import org.eclipse.swt.widgets.Group;
73
import org.eclipse.swt.widgets.Label;
77
import org.eclipse.swt.widgets.Label;
78
import org.eclipse.swt.widgets.Shell;
74
import org.eclipse.ui.IWorkbenchPart;
79
import org.eclipse.ui.IWorkbenchPart;
80
import org.eclipse.ui.IWorkingSet;
81
import org.eclipse.ui.IWorkingSetManager;
82
import org.eclipse.ui.PlatformUI;
83
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
75
84
76
/**
85
/**
77
 * Main page for the wizard that creates the new MIDlet project.
86
 * Main page for the wizard that creates the new MIDlet project.
Lines 97-102 Link Here
97
106
98
                public void activeMTJRuntimeSwitched(
107
                public void activeMTJRuntimeSwitched(
99
                        SwitchActiveMTJRuntimeEvent event) {
108
                        SwitchActiveMTJRuntimeEvent event) {
109
                    fireEvent();
100
                }
110
                }
101
111
102
                /**
112
                /**
Lines 141-147 Link Here
141
        }
151
        }
142
152
143
        public IDevice getSelectedDevice() {
153
        public IDevice getSelectedDevice() {
144
            return configManager.getActiveConfiguration().getDevice();
154
            MTJRuntime activeConfiguration = configManager.getActiveConfiguration();
155
            if(activeConfiguration == null) {
156
                return null;
157
            }
158
            return activeConfiguration.getDevice();
145
        }
159
        }
146
160
147
        private void initConfigManager(Composite configComposite) {
161
        private void initConfigManager(Composite configComposite) {
Lines 485-490 Link Here
485
        }
499
        }
486
    }
500
    }
487
501
502
    private final class WorkingSetGroup extends Observable implements Observer,
503
            IStringButtonAdapter, IComboButtonAdapter, IDialogFieldListener {
504
505
        private SelectionButtonDialogField addWorkingSetButton;
506
        private ComboButtonDialogField workingSetsSelection;
507
        private IWorkingSetManager workingSetManager;
508
509
        private IWorkingSet workingSet;
510
511
        public WorkingSetGroup() {
512
            workingSetManager = PlatformUI.getWorkbench()
513
                    .getWorkingSetManager();
514
515
            addWorkingSetButton = new SelectionButtonDialogField(SWT.CHECK);
516
            addWorkingSetButton.setDialogFieldListener(this);
517
            addWorkingSetButton
518
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageOne_locationGroup_workingSetsButton);
519
520
            workingSetsSelection = new ComboButtonDialogField(this,
521
                    SWT.READ_ONLY);
522
            workingSetsSelection
523
                    .setLabelText(MTJUIMessages.NewMidletProjectWizardPageOne_workingSetGroup_selection);
524
            workingSetsSelection
525
                    .setButtonLabel(MTJUIMessages.NewMidletProjectWizardPageOne_workingSetGroup_select_button);
526
527
            IWorkingSet[] recentWorkingSets = workingSetManager
528
                    .getRecentWorkingSets();
529
            String[] items = new String[recentWorkingSets.length];
530
            int i = 0;
531
            for (IWorkingSet workingSet : recentWorkingSets) {
532
                items[i] = workingSet.getName();
533
                i++;
534
            }
535
            workingSetsSelection.setItems(items);
536
            workingSetsSelection.setDialogFieldListener(this);
537
538
            addWorkingSetButton.setSelection(false);
539
            addWorkingSetButton.attachDialogField(workingSetsSelection);
540
        }
541
542
        public void dialogFieldChanged(DialogField field) {
543
            if (field == workingSetsSelection) {
544
                workingSet = workingSetManager
545
                        .getWorkingSet(workingSetsSelection.getText());
546
            } else if (field == addWorkingSetButton) {
547
                if (workingSetsSelection.getText().equals("")) {
548
                    String[] items = workingSetsSelection.getItems();
549
                    if (items.length > 0) {
550
                        workingSetsSelection.setText(items[0]);
551
                    }
552
                }
553
            }
554
            fireEvent();
555
        }
556
557
        public void changeControlPressed(DialogField field) {
558
            Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
559
                    .getShell();
560
            IWorkingSetSelectionDialog workingSetWizard = workingSetManager
561
                    .createWorkingSetSelectionDialog(shell, false);
562
            if (workingSetWizard != null) {
563
                if (workingSetWizard.open() == Window.OK) {
564
                    workingSet = workingSetWizard.getSelection()[0];
565
                    List<String> items = new ArrayList<String>(Arrays
566
                            .asList(workingSetsSelection.getItems()));
567
                    String workingSetName = workingSet.getName();
568
                    items.add(workingSetName);
569
                    workingSetsSelection.setItems(items
570
                            .toArray(new String[items.size()]));
571
                    workingSetsSelection.setText(workingSetName);
572
                }
573
            }
574
            fireEvent();
575
        }
576
577
        public void update(Observable o, Object arg) {
578
            fireEvent();
579
        }
580
581
        public Control createControl(Composite composite) {
582
            final int numColumns = 3;
583
584
            final Group group = new Group(composite, SWT.NONE);
585
            group.setLayout(initGridLayout(new GridLayout(numColumns, false),
586
                    true));
587
            group
588
                    .setText(MTJUIMessages.NewMidletProjectWizardPageOne_workingSetGroup_contents);
589
590
            addWorkingSetButton.doFillIntoGrid(group, numColumns);
591
            workingSetsSelection.doFillIntoGrid(group, numColumns);
592
593
            return group;
594
        }
595
596
        public boolean isProjectAddedWorkingSet() {
597
            return addWorkingSetButton.isSelected();
598
        }
599
600
        protected void fireEvent() {
601
            setChanged();
602
            notifyObservers();
603
        }
604
605
        public IWorkingSet getWorkingSet() {
606
            return workingSet;
607
        }
608
609
    }
610
488
    /**
611
    /**
489
     * Request a project name. Fires an event whenever the text field is
612
     * Request a project name. Fires an event whenever the text field is
490
     * changed, regardless of its content.
613
     * changed, regardless of its content.
Lines 489-495 Link Here
489
     * Request a project name. Fires an event whenever the text field is
612
     * Request a project name. Fires an event whenever the text field is
490
     * changed, regardless of its content.
613
     * changed, regardless of its content.
491
     */
614
     */
492
    private final class ProjectNameGroup extends Observable implements
615
    public final class ProjectNameGroup extends Observable implements
493
            IDialogFieldListener {
616
            IDialogFieldListener {
494
617
495
        protected final StringDialogField projNameField;
618
        protected final StringDialogField projNameField;
Lines 678-683 Link Here
678
                setPageComplete(false);
801
                setPageComplete(false);
679
                return;
802
                return;
680
            }
803
            }
804
            
805
            if(workingSetGroup.isProjectAddedWorkingSet() && getWorkingSet() == null) {
806
                setErrorMessage(MTJUIMessages.NewMidletProjectWizardPageOne_workingSet_null);
807
                setPageComplete(false);
808
                return;
809
            }
681
810
682
            setPageComplete(true);
811
            setPageComplete(true);
683
            setErrorMessage(null);
812
            setErrorMessage(null);
Lines 765-773 Link Here
765
894
766
    private final JadNameGroup jadNameGroup;
895
    private final JadNameGroup jadNameGroup;
767
896
768
    private Button preprocessedButton;
769
770
    private boolean preprocessingEnabled;
771
    private final LocationGroup projectLocationGroup;
897
    private final LocationGroup projectLocationGroup;
772
898
773
    private final ProjectNameGroup projectNameGroup;
899
    private final ProjectNameGroup projectNameGroup;
Lines 774-779 Link Here
774
900
775
    private final Validator wizardPageValidator;
901
    private final Validator wizardPageValidator;
776
902
903
    private final WorkingSetGroup workingSetGroup;
904
777
    /**
905
    /**
778
     * Creates a new NewMidletProjectWizardPageOne
906
     * Creates a new NewMidletProjectWizardPageOne
779
     */
907
     */
Lines 786-791 Link Here
786
        projectNameGroup = new ProjectNameGroup();
914
        projectNameGroup = new ProjectNameGroup();
787
        jadNameGroup = new JadNameGroup();
915
        jadNameGroup = new JadNameGroup();
788
        projectLocationGroup = new LocationGroup();
916
        projectLocationGroup = new LocationGroup();
917
        workingSetGroup = new WorkingSetGroup();
789
        configurationGroup = new ConfigurationGroup();
918
        configurationGroup = new ConfigurationGroup();
790
919
791
        // establish connections
920
        // establish connections
Lines 801-806 Link Here
801
        configurationGroup.addObserver(wizardPageValidator);
930
        configurationGroup.addObserver(wizardPageValidator);
802
        projectLocationGroup.addObserver(wizardPageValidator);
931
        projectLocationGroup.addObserver(wizardPageValidator);
803
        jadNameGroup.addObserver(wizardPageValidator);
932
        jadNameGroup.addObserver(wizardPageValidator);
933
        workingSetGroup.addObserver(wizardPageValidator);
804
934
805
        // initialize defaults
935
        // initialize defaults
806
        setProjectName(""); //$NON-NLS-1$
936
        setProjectName(""); //$NON-NLS-1$
Lines 817-823 Link Here
817
     */
947
     */
818
    public void createControl(final Composite parent) {
948
    public void createControl(final Composite parent) {
819
        initializeDialogUnits(parent);
949
        initializeDialogUnits(parent);
820
    	
950
821
        ScrolledComposite scrolledComposite = new ScrolledComposite(parent,
951
        ScrolledComposite scrolledComposite = new ScrolledComposite(parent,
822
                SWT.V_SCROLL | SWT.H_SCROLL);
952
                SWT.V_SCROLL | SWT.H_SCROLL);
823
        scrolledComposite.setExpandHorizontal(true);
953
        scrolledComposite.setExpandHorizontal(true);
Lines 822-833 Link Here
822
                SWT.V_SCROLL | SWT.H_SCROLL);
952
                SWT.V_SCROLL | SWT.H_SCROLL);
823
        scrolledComposite.setExpandHorizontal(true);
953
        scrolledComposite.setExpandHorizontal(true);
824
        scrolledComposite.setExpandVertical(true);
954
        scrolledComposite.setExpandVertical(true);
825
		scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
955
        scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
826
        
956
                true));
957
827
        final Composite composite = new Composite(scrolledComposite, SWT.NONE);
958
        final Composite composite = new Composite(scrolledComposite, SWT.NONE);
828
        composite.setFont(parent.getFont());
959
        composite.setFont(parent.getFont());
829
        composite.setLayout(initGridLayout(new GridLayout(1, false), true));
960
        composite.setLayout(initGridLayout(new GridLayout(1, false), true));
830
        
961
831
        // create UI elements
962
        // create UI elements
832
        Control nameControl = createNameControl(composite);
963
        Control nameControl = createNameControl(composite);
833
        nameControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
964
        nameControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Lines 841-852 Link Here
841
        Control configControl = createConfigGroupControl(composite);
972
        Control configControl = createConfigGroupControl(composite);
842
        configControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
973
        configControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
843
974
844
        Control preprocessorControl = createPreprocessorGroupSelectionControl(composite);
975
        Control workingSets = createWorkingSets(composite);
845
        preprocessorControl
976
        workingSets.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
846
                .setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
847
977
848
        scrolledComposite.setContent(composite);
978
        scrolledComposite.setContent(composite);
849
        scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
979
        scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT,
980
                SWT.DEFAULT));
850
        setControl(scrolledComposite);
981
        setControl(scrolledComposite);
851
    }
982
    }
852
983
Lines 921-926 Link Here
921
    }
1052
    }
922
1053
923
    /**
1054
    /**
1055
     * @return the projectNameGroup
1056
     */
1057
    public Observable getProjectNameGroup() {
1058
        return projectNameGroup;
1059
    }
1060
1061
    /**
1062
     * @return the configurationGroup
1063
     */
1064
    public Observable getConfigurationGroup() {
1065
        return configurationGroup;
1066
    }
1067
1068
    /**
924
     * Returns the compiler compliance to be used for the project, or
1069
     * Returns the compiler compliance to be used for the project, or
925
     * <code>null</code> to use the workspace compiler compliance.
1070
     * <code>null</code> to use the workspace compiler compliance.
926
     * 
1071
     * 
Lines 963-978 Link Here
963
    }
1108
    }
964
1109
965
    /**
1110
    /**
966
     * Return a boolean concerning whether preprocessing is enabled for the
967
     * newly created project.
968
     * 
969
     * @return the preprocessingEnabled
970
     */
971
    public boolean isPreprocessingEnabled() {
972
        return preprocessingEnabled;
973
    }
974
975
    /**
976
     * Sets the project location of the new project or <code>null</code> if the
1111
     * Sets the project location of the new project or <code>null</code> if the
977
     * project should be created in the workspace
1112
     * project should be created in the workspace
978
     * 
1113
     * 
Lines 1059-1098 Link Here
1059
        return projectNameGroup.createControl(composite);
1194
        return projectNameGroup.createControl(composite);
1060
    }
1195
    }
1061
1196
1062
    /**
1197
    protected Control createWorkingSets(Composite composite) {
1063
     * @param composite
1064
     * @return
1065
     */
1066
    protected Control createPreprocessorGroupSelectionControl(
1067
            Composite composite) {
1068
1198
1069
        // Add an extra composite to get the layout to match up the
1199
        return workingSetGroup.createControl(composite);
1070
        // components vertically
1200
    }
1071
        Group preprocessorGroup = new Group(composite, SWT.NONE);
1072
        preprocessorGroup.setLayout(new GridLayout(1, true));
1073
        preprocessorGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
1074
        preprocessorGroup
1075
                .setText(MTJUIMessages.NewMidletProjectWizardPageOne_preprocessorGroup);
1076
1077
        preprocessedButton = new Button(preprocessorGroup, SWT.CHECK);
1078
        preprocessedButton
1079
                .setText(MTJUIMessages.NewMidletProjectWizardPageOne_preprocessor);
1080
        preprocessedButton
1081
                .setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
1082
        preprocessedButton.addSelectionListener(new SelectionAdapter() {
1083
1201
1084
            /*
1202
    public IWorkingSet getWorkingSet() {
1085
             * (non-Javadoc)
1203
        return workingSetGroup.getWorkingSet();
1086
             * @see
1087
             * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse
1088
             * .swt.events.SelectionEvent)
1089
             */
1090
            @Override
1091
            public void widgetSelected(SelectionEvent e) {
1092
                preprocessingEnabled = preprocessedButton.getSelection();
1093
            }
1094
        });
1095
        return preprocessorGroup;
1096
    }
1204
    }
1097
1205
1098
    /*
1206
    /*
(-)src/org/eclipse/mtj/internal/ui/wizards/projects/NewMidletProjectWizardPageJavaSettings.java (+949 lines)
Line 0 Link Here
1
/**
2
 * Copyright (c) 2008 Motorola.
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
 *     Diego Sandin (Motorola) - Initial version
11
 *     Feng Wang (Sybase)      - Add configurations into Metadata for Multi-Configs
12
 *                               support.
13
 *     Diego Sandin (Motorola) - Use Eclipse Message Bundles [Bug 255874]
14
 */
15
package org.eclipse.mtj.internal.ui.wizards.projects;
16
17
import java.io.File;
18
import java.io.FileInputStream;
19
import java.io.FileOutputStream;
20
import java.io.IOException;
21
import java.io.InputStream;
22
import java.io.OutputStream;
23
import java.lang.reflect.InvocationTargetException;
24
import java.net.URI;
25
import java.net.URISyntaxException;
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.HashSet;
29
import java.util.List;
30
import java.util.Map;
31
import java.util.Vector;
32
33
import org.eclipse.core.filesystem.EFS;
34
import org.eclipse.core.filesystem.IFileInfo;
35
import org.eclipse.core.filesystem.IFileStore;
36
import org.eclipse.core.resources.IFolder;
37
import org.eclipse.core.resources.IProject;
38
import org.eclipse.core.resources.IResource;
39
import org.eclipse.core.resources.IResourceStatus;
40
import org.eclipse.core.resources.IWorkspaceDescription;
41
import org.eclipse.core.resources.IWorkspaceRoot;
42
import org.eclipse.core.resources.ResourcesPlugin;
43
import org.eclipse.core.runtime.Assert;
44
import org.eclipse.core.runtime.CoreException;
45
import org.eclipse.core.runtime.IAdaptable;
46
import org.eclipse.core.runtime.IPath;
47
import org.eclipse.core.runtime.IProgressMonitor;
48
import org.eclipse.core.runtime.IStatus;
49
import org.eclipse.core.runtime.NullProgressMonitor;
50
import org.eclipse.core.runtime.OperationCanceledException;
51
import org.eclipse.core.runtime.Path;
52
import org.eclipse.core.runtime.Preferences;
53
import org.eclipse.core.runtime.Status;
54
import org.eclipse.core.runtime.SubProgressMonitor;
55
import org.eclipse.jdt.core.IClasspathEntry;
56
import org.eclipse.jdt.core.IJavaProject;
57
import org.eclipse.jdt.core.JavaCore;
58
import org.eclipse.jdt.ui.PreferenceConstants;
59
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
60
import org.eclipse.jface.dialogs.ErrorDialog;
61
import org.eclipse.jface.operation.IRunnableWithProgress;
62
import org.eclipse.jface.preference.IPreferenceStore;
63
import org.eclipse.mtj.core.MTJCore;
64
import org.eclipse.mtj.core.project.IMetaData;
65
import org.eclipse.mtj.core.project.ProjectType;
66
import org.eclipse.mtj.core.project.runtime.MTJRuntimeList;
67
import org.eclipse.mtj.core.sdk.device.IDevice;
68
import org.eclipse.mtj.core.sdk.device.midp.IMIDPDevice;
69
import org.eclipse.mtj.internal.core.IMTJCoreConstants;
70
import org.eclipse.mtj.internal.core.build.preprocessor.PreprocessorBuilder;
71
import org.eclipse.mtj.internal.core.externallibrary.classpath.ExternalLibraryClasspathContainer;
72
import org.eclipse.mtj.internal.core.externallibrary.manager.ExternalLibraryManager;
73
import org.eclipse.mtj.internal.core.externallibrary.model.IExternalLibrary;
74
import org.eclipse.mtj.internal.core.project.midp.IJADConstants;
75
import org.eclipse.mtj.internal.core.project.midp.JavaMEClasspathContainer;
76
import org.eclipse.mtj.internal.core.project.midp.MidletSuiteFactory;
77
import org.eclipse.mtj.internal.core.util.MTJStatusHandler;
78
import org.eclipse.mtj.internal.ui.IMTJUIConstants;
79
import org.eclipse.mtj.internal.ui.MTJUIMessages;
80
import org.eclipse.mtj.internal.ui.util.ExceptionHandler;
81
import org.eclipse.osgi.util.NLS;
82
import org.eclipse.ui.IWorkingSet;
83
import org.eclipse.ui.IWorkingSetManager;
84
import org.eclipse.ui.PlatformUI;
85
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
86
87
/**
88
 * The New MIDlet Project Java Capability Wizard Page allows the user to
89
 * configure the build path and output location of the MIDlet Project. As
90
 * addition to the {@link JavaCapabilityConfigurationPage}, the wizard page does
91
 * an early project creation (so that linked folders can be defined).
92
 * 
93
 * @author Diego Madruga Sandin
94
 * @since 0.9
95
 */
96
public class NewMidletProjectWizardPageJavaSettings extends
97
        JavaCapabilityConfigurationPage {
98
99
    private static final String FILENAME_CLASSPATH = ".classpath"; //$NON-NLS-1$
100
101
    private static final String FILENAME_PROJECT = ".project"; //$NON-NLS-1$
102
103
    /**
104
     * @param projectName
105
     * @param location
106
     * @return
107
     */
108
    private static URI getRealLocation(String projectName, URI location) {
109
        if (location == null) { // inside workspace
110
            try {
111
                URI rootLocation = MTJCore.getWorkspace().getRoot()
112
                        .getLocationURI();
113
114
                location = new URI(rootLocation.getScheme(), null, Path
115
                        .fromPortableString(rootLocation.getPath()).append(
116
                                projectName).toString(), null);
117
            } catch (URISyntaxException e) {
118
                Assert.isTrue(false, "Can't happen"); //$NON-NLS-1$
119
            }
120
        }
121
        return location;
122
    }
123
124
    public Boolean isAutobuild;
125
    private IProject currProject;
126
    private URI currProjectLocation;
127
    private File fDotClasspathBackup;
128
    private File fDotProjectBackup;
129
    private NewMidletProjectWizardPageOne firstPage;
130
    private NewMidletProjectWizardPageProperties propertiesPage;
131
    private HashSet<IFileStore> fOrginalFolders;
132
133
    private boolean keepContent;
134
135
    private NewMidletProjectWizardPageLibrary pageLibrary;
136
137
    /**
138
     * Creates a new New MIDlet Project Java Capability Wizard Page.
139
     * 
140
     * @param workbench
141
     */
142
    public NewMidletProjectWizardPageJavaSettings(NewMidletProjectWizardPageOne pageOne,
143
            NewMidletProjectWizardPageProperties pageTwo,
144
            NewMidletProjectWizardPageLibrary pageLibrary) {
145
        this.currProjectLocation = null;
146
        this.currProject = null;
147
        this.firstPage = pageOne;
148
        this.propertiesPage = pageTwo;
149
        this.pageLibrary = pageLibrary;
150
        isAutobuild = null;
151
    }
152
153
    /**
154
     * Called from the wizard on cancel.
155
     */
156
    public void performCancel() {
157
        if (currProject != null) {
158
            removeProvisonalProject();
159
        }
160
    }
161
162
    /**
163
     * Called from the wizard on finish.
164
     * 
165
     * @param monitor the progress monitor
166
     * @throws CoreException thrown when the project creation or configuration
167
     *             failed
168
     * @throws InterruptedException thrown when the user canceled the project
169
     *             creation
170
     */
171
    @SuppressWarnings("unchecked")
172
    public void performFinish(IProgressMonitor monitor) throws CoreException,
173
            InterruptedException {
174
        try {
175
176
            monitor
177
                    .beginTask(
178
                            MTJUIMessages.NewMidletProjectWizardPageThree_performFinish_monitor_taskname,
179
                            3);
180
            if (currProject == null) {
181
                updateProject(new SubProgressMonitor(monitor, 1));
182
            }
183
184
            configureJavaProject(new SubProgressMonitor(monitor, 2));
185
186
            if (!keepContent) {
187
                IJavaProject project = JavaCore.create(currProject);
188
                Map options = project.getOptions(false);
189
190
                // complete compliance options
191
                project.setOptions(options);
192
            }
193
194
        } finally {
195
            monitor.done();
196
            currProject = null;
197
            if (isAutobuild != null) {
198
                IWorkspaceDescription description = ResourcesPlugin
199
                        .getWorkspace().getDescription();
200
                description.setAutoBuilding(isAutobuild.booleanValue());
201
                MTJCore.getWorkspace().setDescription(description);
202
                isAutobuild = null;
203
            }
204
        }
205
    }
206
207
    /*
208
     * (non-Javadoc)
209
     * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
210
     */
211
    @Override
212
    public void setVisible(boolean visible) {
213
        boolean isShownFirstTime = visible && (currProject == null);
214
        if (visible) {
215
            if (isShownFirstTime) {
216
                // entering from the first page
217
                createProvisonalProject();
218
            }
219
        } else {
220
            if ((getContainer().getCurrentPage() == firstPage)
221
                    || (getContainer().getCurrentPage() == pageLibrary)) {
222
                // leaving back to previous pages
223
                removeProvisonalProject();
224
            }
225
        }
226
        super.setVisible(visible);
227
        if (isShownFirstTime) {
228
            setFocus();
229
        }
230
    }
231
232
    /**
233
     * Update the java configuration before making the page visible.
234
     */
235
    public void updateConfiguration() {
236
        String projectName = firstPage.getProjectName();
237
238
        currProject = MTJCore.getWorkspace().getRoot().getProject(
239
                projectName);
240
241
        IJavaProject javaProject = JavaCore.create(currProject);
242
        IPath projectPath = currProject.getFullPath();
243
244
        // Initialize the classpath entries using the source directories
245
        // and classpath container
246
        ArrayList<IClasspathEntry> entryList = new ArrayList<IClasspathEntry>();
247
        entryList.add(getSrcPathEntry(projectPath));
248
        addResourcesDirectoryIfRequested(entryList, currProject);
249
        IPath entryPath = new Path(JavaMEClasspathContainer.JAVAME_CONTAINER
250
                + "/" + firstPage.getSelectedDevice()); //$NON-NLS-1$
251
252
        entryList.add(JavaCore.newContainerEntry(entryPath));
253
254
        IClasspathEntry[] entries = entryList
255
                .toArray(new IClasspathEntry[entryList.size()]);
256
257
        init(javaProject, null, entries, false);
258
    }
259
260
    /**
261
     * Add a resources directory as a source path entry if the user preferences
262
     * requested.
263
     * 
264
     * @param entryList
265
     * @param project
266
     */
267
    private void addResourcesDirectoryIfRequested(
268
            List<IClasspathEntry> entryList, IProject project) {
269
        Preferences prefs = MTJCore.getMTJCore().getPluginPreferences();
270
271
        if (useSourceAndBinaryFolders()
272
                && prefs.getBoolean(IMTJCoreConstants.PREF_USE_RESOURCES_DIR)) {
273
            // Create the resources directory if it doesn't already exist
274
            String resDirName = prefs
275
                    .getString(IMTJCoreConstants.PREF_RESOURCES_DIR);
276
            IFolder resFolder = project.getFolder(resDirName);
277
278
            if (!resFolder.exists()) {
279
                try {
280
                    resFolder.create(true, true, new NullProgressMonitor());
281
                } catch (CoreException e) {
282
                    e.printStackTrace();
283
                }
284
            }
285
286
            // Add it as a source folder to the java project
287
            entryList.add(JavaCore.newSourceEntry(resFolder.getFullPath()));
288
        }
289
    }
290
291
    private IStatus changeToNewProject() {
292
        class UpdateRunnable implements IRunnableWithProgress {
293
            public IStatus infoStatus = Status.OK_STATUS;
294
295
            public void run(IProgressMonitor monitor)
296
                    throws InvocationTargetException, InterruptedException {
297
                try {
298
                    if (isAutobuild == null) {
299
                        IWorkspaceDescription description = ResourcesPlugin
300
                                .getWorkspace().getDescription();
301
                        isAutobuild = Boolean.valueOf(description
302
                                .isAutoBuilding());
303
                        description.setAutoBuilding(false);
304
                        MTJCore.getWorkspace().setDescription(
305
                                description);
306
                    }
307
                    infoStatus = updateProject(monitor);
308
                } catch (CoreException e) {
309
                    throw new InvocationTargetException(e);
310
                } catch (OperationCanceledException e) {
311
                    throw new InterruptedException();
312
                } finally {
313
                    monitor.done();
314
                }
315
            }
316
        }
317
318
        UpdateRunnable op = new UpdateRunnable();
319
        try {
320
            getContainer().run(true, false,
321
                    new WorkspaceModifyDelegatingOperation(op));
322
323
            return op.infoStatus;
324
        } catch (InvocationTargetException e) {
325
326
            final String title = MTJUIMessages.NewMidletProjectWizardPageThree_changeToNewProject_errordialog_title;
327
            final String message = MTJUIMessages.NewMidletProjectWizardPageThree_changeToNewProject_errordialog_message;
328
            ExceptionHandler.handle(e, getShell(), title, message);
329
330
        } catch (InterruptedException e) {
331
            // cancel pressed
332
        }
333
        return null;
334
    }
335
336
    /**
337
     * @param source
338
     * @param target
339
     * @param monitor
340
     * @throws IOException
341
     * @throws CoreException
342
     */
343
    private void copyFile(File source, IFileStore target,
344
            IProgressMonitor monitor) throws IOException, CoreException {
345
        FileInputStream is = new FileInputStream(source);
346
        OutputStream os = target.openOutputStream(EFS.NONE, monitor);
347
        copyFile(is, os);
348
    }
349
350
    /**
351
     * @param source
352
     * @param target
353
     * @throws IOException
354
     * @throws CoreException
355
     */
356
    private void copyFile(IFileStore source, File target) throws IOException,
357
            CoreException {
358
        InputStream is = source.openInputStream(EFS.NONE, null);
359
        FileOutputStream os = new FileOutputStream(target);
360
        copyFile(is, os);
361
    }
362
363
    /**
364
     * @param is
365
     * @param os
366
     * @throws IOException
367
     */
368
    private void copyFile(InputStream is, OutputStream os) throws IOException {
369
        try {
370
            byte[] buffer = new byte[8192];
371
            while (true) {
372
                int bytesRead = is.read(buffer);
373
                if (bytesRead == -1) {
374
                    break;
375
                }
376
377
                os.write(buffer, 0, bytesRead);
378
            }
379
        } finally {
380
            try {
381
                is.close();
382
            } finally {
383
                os.close();
384
            }
385
        }
386
    }
387
388
    /**
389
     * @param source
390
     * @param name
391
     * @return
392
     * @throws CoreException
393
     */
394
    private File createBackup(IFileStore source, String name)
395
            throws CoreException {
396
        try {
397
            File bak = File.createTempFile("eclipse-" + name, ".bak"); //$NON-NLS-1$//$NON-NLS-2$
398
            copyFile(source, bak);
399
            return bak;
400
        } catch (IOException e) {
401
            IStatus status = new Status(
402
                    IStatus.ERROR,
403
                    IMTJUIConstants.PLUGIN_ID,
404
                    IStatus.ERROR,
405
                    MTJUIMessages.NewMidletProjectWizardPageThree_createBackup_error_1
406
                            + name
407
                            + MTJUIMessages.NewMidletProjectWizardPageThree_createBackup_error_2,
408
                    e);
409
            throw new CoreException(status);
410
        }
411
    }
412
413
    private void deleteProjectFile(URI projectLocation) throws CoreException {
414
        IFileStore file = EFS.getStore(projectLocation);
415
        if (file.fetchInfo().exists()) {
416
            IFileStore projectFile = file.getChild(FILENAME_PROJECT);
417
            if (projectFile.fetchInfo().exists()) {
418
                projectFile.delete(EFS.NONE, null);
419
            }
420
        }
421
    }
422
423
    private final void doRemoveProject(IProgressMonitor monitor)
424
            throws InvocationTargetException {
425
        final boolean noProgressMonitor = (currProjectLocation == null); // inside
426
        // workspace
427
        if ((monitor == null) || noProgressMonitor) {
428
            monitor = new NullProgressMonitor();
429
        }
430
        monitor
431
                .beginTask(
432
                        MTJUIMessages.NewMidletProjectWizardPageThree_doRemoveProject_taskname,
433
                        3);
434
        try {
435
            try {
436
                URI projLoc = currProject.getLocationURI();
437
438
                boolean removeContent = !keepContent
439
                        && currProject.isSynchronized(IResource.DEPTH_INFINITE);
440
                if ((!removeContent)
441
                        && (currProject.getProject().getFullPath().toFile()
442
                                .exists())) {
443
                    restoreExistingFolders(projLoc);
444
                }
445
                currProject.delete(removeContent, false,
446
                        new SubProgressMonitor(monitor, 2));
447
448
                MidletSuiteFactory.removeMidletSuiteProject(getJavaProject());
449
450
                restoreExistingFiles(projLoc,
451
                        new SubProgressMonitor(monitor, 1));
452
            } finally {
453
                IWorkspaceDescription description = ResourcesPlugin
454
                        .getWorkspace().getDescription();
455
                description.setAutoBuilding(isAutobuild.booleanValue());
456
                MTJCore.getWorkspace().setDescription(description);
457
                // isAutobuild must be set
458
                isAutobuild = null;
459
            }
460
        } catch (CoreException e) {
461
            throw new InvocationTargetException(e);
462
        } finally {
463
            monitor.done();
464
            currProject = null;
465
            keepContent = false;
466
        }
467
    }
468
469
    /**
470
     * Get the source path for the project taking into account the new project
471
     * preferences that the user has specified.
472
     * 
473
     * @param projectPath
474
     * @return
475
     */
476
    private IPath getSrcPath(IPath projectPath) {
477
        IPath srcPath = projectPath;
478
479
        if (useSourceAndBinaryFolders()) {
480
            IPreferenceStore store = PreferenceConstants.getPreferenceStore();
481
            String srcPathName = store
482
                    .getString(PreferenceConstants.SRCBIN_SRCNAME);
483
            srcPath = projectPath.append(srcPathName);
484
        }
485
486
        return srcPath;
487
    }
488
489
    /**
490
     * Return an IClasspathEntry for the source path.
491
     * 
492
     * @param projectPath
493
     * @return
494
     */
495
    private IClasspathEntry getSrcPathEntry(IPath projectPath) {
496
        IPath srcPath = getSrcPath(projectPath);
497
498
        // Set up exclusions for the verified and deployed directories
499
        // if the source and project directories are the same
500
        IPath[] exclusions = null;
501
        if (srcPath.equals(projectPath)) {
502
            exclusions = new IPath[3];
503
            exclusions[0] = new Path(MTJCore.getDeploymentDirectoryName() + "/"); //$NON-NLS-1$
504
            exclusions[1] = new Path(IMTJCoreConstants.TEMP_FOLDER_NAME + "/"); //$NON-NLS-1$
505
            exclusions[2] = new Path(PreprocessorBuilder.PROCESSED_DIRECTORY
506
                    + "/"); //$NON-NLS-1$
507
        } else {
508
            exclusions = new IPath[0];
509
        }
510
511
        return JavaCore.newSourceEntry(srcPath, exclusions);
512
    }
513
514
    /**
515
     * @param realLocation
516
     * @return
517
     * @throws CoreException
518
     */
519
    private boolean hasExistingContent(URI realLocation) throws CoreException {
520
        IFileStore file = EFS.getStore(realLocation);
521
        return file.fetchInfo().exists();
522
    }
523
524
    private void rememberExisitingFolders(URI projectLocation) {
525
        fOrginalFolders = new HashSet<IFileStore>();
526
527
        try {
528
            IFileStore[] children = EFS.getStore(projectLocation).childStores(
529
                    EFS.NONE, null);
530
            for (IFileStore child : children) {
531
                IFileInfo info = child.fetchInfo();
532
                if (info.isDirectory() && info.exists()
533
                        && !fOrginalFolders.contains(child.getName())) {
534
                    fOrginalFolders.add(child);
535
                }
536
            }
537
        } catch (CoreException e) {
538
            final String title = MTJUIMessages.NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_title;
539
            final String message = MTJUIMessages.NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_message;
540
            ExceptionHandler.handle(e, getShell(), title, message);
541
        }
542
    }
543
544
    private void rememberExistingFiles(URI projectLocation)
545
            throws CoreException {
546
        fDotProjectBackup = null;
547
        fDotClasspathBackup = null;
548
549
        IFileStore file = EFS.getStore(projectLocation);
550
        if (file.fetchInfo().exists()) {
551
            IFileStore projectFile = file.getChild(FILENAME_PROJECT);
552
            if (projectFile.fetchInfo().exists()) {
553
                fDotProjectBackup = createBackup(projectFile, "project-desc"); //$NON-NLS-1$ 
554
            }
555
            IFileStore classpathFile = file.getChild(FILENAME_CLASSPATH);
556
            if (classpathFile.fetchInfo().exists()) {
557
                fDotClasspathBackup = createBackup(classpathFile,
558
                        "classpath-desc"); //$NON-NLS-1$ 
559
            }
560
        }
561
    }
562
563
    private void restoreExistingFiles(URI projectLocation,
564
            IProgressMonitor monitor) throws CoreException {
565
        int ticks = ((fDotProjectBackup != null ? 1 : 0) + (fDotClasspathBackup != null ? 1
566
                : 0)) * 2;
567
        monitor.beginTask("", ticks); //$NON-NLS-1$
568
        try {
569
            IFileStore projectFile = EFS.getStore(projectLocation).getChild(
570
                    FILENAME_PROJECT);
571
            projectFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
572
            if (fDotProjectBackup != null) {
573
                copyFile(fDotProjectBackup, projectFile,
574
                        new SubProgressMonitor(monitor, 1));
575
            }
576
        } catch (IOException e) {
577
            IStatus status = new Status(
578
                    IStatus.ERROR,
579
                    IMTJUIConstants.PLUGIN_ID,
580
                    IStatus.ERROR,
581
                    MTJUIMessages.NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotproject,
582
                    e);
583
            throw new CoreException(status);
584
        }
585
        try {
586
            IFileStore classpathFile = EFS.getStore(projectLocation).getChild(
587
                    FILENAME_CLASSPATH);
588
            classpathFile.delete(EFS.NONE, new SubProgressMonitor(monitor, 1));
589
            if (fDotClasspathBackup != null) {
590
                copyFile(fDotClasspathBackup, classpathFile,
591
                        new SubProgressMonitor(monitor, 1));
592
            }
593
        } catch (IOException e) {
594
            IStatus status = new Status(
595
                    IStatus.ERROR,
596
                    IMTJUIConstants.PLUGIN_ID,
597
                    IStatus.ERROR,
598
                    MTJUIMessages.NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotclasspath,
599
                    e);
600
            throw new CoreException(status);
601
        }
602
    }
603
604
    private void restoreExistingFolders(URI projectLocation) {
605
        try {
606
            IFileStore[] children = EFS.getStore(projectLocation).childStores(
607
                    EFS.NONE, null);
608
            for (IFileStore child : children) {
609
                IFileInfo info = child.fetchInfo();
610
                if (info.isDirectory() && info.exists()
611
                        && !fOrginalFolders.contains(child)) {
612
                    child.delete(EFS.NONE, null);
613
                    fOrginalFolders.remove(child);
614
                }
615
            }
616
617
            for (IFileStore fileStore : fOrginalFolders) {
618
                IFileStore deleted = fileStore;
619
                deleted.mkdir(EFS.NONE, null);
620
            }
621
        } catch (CoreException e) {
622
            final String title = MTJUIMessages.NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_title;
623
            final String message = MTJUIMessages.NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_message;
624
            ExceptionHandler.handle(e, getShell(), title, message);
625
        }
626
    }
627
628
    /**
629
     * @param monitor
630
     * @return
631
     * @throws CoreException
632
     * @throws InterruptedException
633
     */
634
    private final IStatus updateProject(IProgressMonitor monitor)
635
            throws CoreException, InterruptedException {
636
        IStatus result = Status.OK_STATUS;
637
        if (monitor == null) {
638
            monitor = new NullProgressMonitor();
639
        }
640
        try {
641
            monitor
642
                    .beginTask(
643
                            MTJUIMessages.NewMidletProjectWizardPageThree_updateProject_taskname,
644
                            7);
645
            if (monitor.isCanceled()) {
646
                throw new OperationCanceledException();
647
            }
648
649
            String projectName = firstPage.getProjectName();
650
651
            currProject = MTJCore.getWorkspace().getRoot().getProject(
652
                    projectName);
653
            currProjectLocation = firstPage.getProjectLocationURI();
654
655
            URI realLocation = getRealLocation(projectName, currProjectLocation);
656
            keepContent = hasExistingContent(realLocation);
657
658
            if (monitor.isCanceled()) {
659
                throw new OperationCanceledException();
660
            }
661
662
            if (keepContent) {
663
                rememberExistingFiles(realLocation);
664
                rememberExisitingFolders(realLocation);
665
            }
666
667
            if (monitor.isCanceled()) {
668
                throw new OperationCanceledException();
669
            }
670
671
            try {
672
673
                JavaCapabilityConfigurationPage.createProject(currProject,
674
                        firstPage.getProjectLocationURI(),
675
                        new SubProgressMonitor(monitor, 1));
676
677
                // Set the device into the project metadata to make
678
                // the java project creation happy.
679
                IDevice device = firstPage.getSelectedDevice();
680
                MTJRuntimeList configurations = firstPage.getConfigurations();
681
                // Make up Metadata and save it.
682
                IMetaData metadata = MTJCore.createMetaData(currProject,
683
                        ProjectType.MIDLET_SUITE);
684
                metadata.setMTJRuntimeList(configurations);
685
                try {
686
                    metadata.saveMetaData();
687
                } catch (CoreException e) {
688
                    throw new InvocationTargetException(e);
689
                }
690
691
                updateConfiguration();
692
693
                // Get the java nature
694
                try {
695
                    IRunnableWithProgress progress = super.getRunnable();
696
                    progress.run(monitor);
697
                } catch (Throwable e) {
698
                    throw new CoreException(new Status(
699
                            IResourceStatus.FAILED_READ_METADATA, "", e //$NON-NLS-1$
700
                                    .getMessage()));
701
                }
702
703
                // Get the J2ME nature and metadata set up
704
                String jadFileName = firstPage.getJadFileName();
705
706
                IJavaProject javaProject = super.getJavaProject();
707
708
                MidletSuiteFactory.MidletSuiteCreationRunnable runnable = MidletSuiteFactory
709
                        .getMidletSuiteCreationRunnable(currProject,
710
                                javaProject, (IMIDPDevice) device, jadFileName);
711
712
                Map<String, String> properties = new HashMap<String, String>();
713
                properties.put(IJADConstants.JAD_MIDLET_NAME, propertiesPage.getMIDletName());
714
                properties.put(IJADConstants.JAD_MIDLET_VENDOR, propertiesPage.getMIDletVendor());
715
                properties.put(IJADConstants.JAD_MIDLET_VERSION, propertiesPage.getMIDletVersion());
716
                properties.put(IJADConstants.JAD_MICROEDITION_CONFIG, propertiesPage.getMeConfiguration());
717
                properties.put(IJADConstants.JAD_MICROEDITION_PROFILE, propertiesPage.getMeProfile());
718
                
719
                runnable.setProperties(properties);
720
                
721
                
722
                runnable.setPreprocessingEnable(propertiesPage
723
                        .isPreprocessingEnabled());
724
                
725
                boolean localizationEnabled = propertiesPage
726
                .isLocalizationEnabled();
727
                runnable.setLocalizationEnabled(localizationEnabled);
728
                if (localizationEnabled) {
729
                    runnable.setPropertiesFolderName(propertiesPage
730
                            .getPropertiesFolderName());
731
                    runnable.setPackageName(propertiesPage.getPackageName());
732
                }
733
                runnable.setJMUnitSupport(propertiesPage.isJMUnitEnabled());
734
735
                runnable.run(monitor);
736
                
737
                IAdaptable[] adaptableElements = new IAdaptable[] { currProject };
738
                IWorkingSet workingSet = firstPage.getWorkingSet();
739
                if (workingSet != null) {
740
                    List<IAdaptable> list = new Vector<IAdaptable>();
741
742
                    for (IAdaptable adaptable : workingSet.getElements()) {
743
                        list.add(adaptable);
744
                    }
745
                    for (IAdaptable adaptable : workingSet
746
                            .adaptElements(adaptableElements)) {
747
                        list.add(adaptable);
748
                    }
749
                    IAdaptable[] newElements = new IAdaptable[list.size()];
750
                    workingSet.setElements(list.toArray(newElements));
751
                    IWorkingSetManager workingSetManager = PlatformUI
752
                            .getWorkbench().getWorkingSetManager();
753
                    workingSetManager.addRecentWorkingSet(workingSet);
754
                }
755
756
757
            } catch (CoreException e) {
758
                if (e.getStatus().getCode() == IResourceStatus.FAILED_READ_METADATA) {
759
                    result = new Status(
760
                            IStatus.INFO,
761
                            IMTJUIConstants.PLUGIN_ID,
762
                            MTJUIMessages.NewMidletProjectWizardPageThree_updateProject_fail_read_metadata);
763
764
                    deleteProjectFile(realLocation);
765
                    if (currProject.exists()) {
766
                        currProject.delete(true, null);
767
                    }
768
769
                    createProject(currProject, currProjectLocation, null);
770
                } else {
771
                    throw e;
772
                }
773
            } catch (Throwable e) {
774
                throw new CoreException(Status.CANCEL_STATUS);
775
            }
776
777
            if (monitor.isCanceled()) {
778
                throw new OperationCanceledException();
779
            }
780
781
            initializeBuildPath(JavaCore.create(currProject),
782
                    new SubProgressMonitor(monitor, 2));
783
784
            configureJavaProject(new SubProgressMonitor(monitor, 3));
785
            // create the Java project to allow the use of the new source folder
786
            // page
787
        } catch (Exception e) {
788
            throw new CoreException(Status.CANCEL_STATUS);
789
        } finally {
790
            monitor.done();
791
        }
792
793
        return result;
794
    }
795
796
    /**
797
     * Return a boolean indicating whether there will be separate source and
798
     * binary folders in the project.
799
     * 
800
     * @return
801
     */
802
    private boolean useSourceAndBinaryFolders() {
803
        IPreferenceStore store = PreferenceConstants.getPreferenceStore();
804
        return store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
805
    }
806
807
    /**
808
     * Creates the provisional project on which the wizard is working on. The
809
     * provisional project is typically created when the page is entered the
810
     * first time. The early project creation is required to configure linked
811
     * folders.
812
     * 
813
     * @return the provisional project
814
     */
815
    protected IProject createProvisonalProject() {
816
        IStatus status = changeToNewProject();
817
        if ((status != null) && !status.isOK()) {
818
            ErrorDialog.openError(getShell(), "createProvisonalProject", null, //$NON-NLS-1$
819
                    status);
820
        }
821
        return currProject;
822
    }
823
824
    /**
825
     * Evaluates the new build path and output folder according to the settings
826
     * on the first page. The resulting build path is set by calling
827
     * {@link #init(IJavaProject, IPath, IClasspathEntry[], boolean)}. Clients
828
     * can override this method.
829
     * 
830
     * @param javaProject the new project which is already created when this
831
     *            method is called.
832
     * @param monitor the progress monitor
833
     * @throws CoreException thrown when initializing the build path failed
834
     */
835
    protected void initializeBuildPath(IJavaProject javaProject,
836
            IProgressMonitor monitor) throws CoreException {
837
        if (monitor == null) {
838
            monitor = new NullProgressMonitor();
839
        }
840
        monitor
841
                .beginTask(
842
                        MTJUIMessages.NewMidletProjectWizardPageThree_updateProject_monitor_buildpath_name,
843
                        2);
844
845
        try {
846
            IClasspathEntry[] entries = null;
847
            IProject project = javaProject.getProject();
848
849
            List<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
850
            IWorkspaceRoot root = project.getWorkspace().getRoot();
851
852
            IClasspathEntry sourceClasspathEntry = getSrcPathEntry(project
853
                    .getFullPath());
854
855
            if (sourceClasspathEntry.getPath() != project.getFullPath()) {
856
857
                IFolder folder = root.getFolder(sourceClasspathEntry.getPath());
858
859
                if (!folder.exists()) {
860
                    folder.create(true, true,
861
                            new SubProgressMonitor(monitor, 1));
862
                }
863
            }
864
            cpEntries.add(sourceClasspathEntry);
865
            addResourcesDirectoryIfRequested(cpEntries, project);
866
867
            IPath entryPath = new Path(
868
                    JavaMEClasspathContainer.JAVAME_CONTAINER + "/" //$NON-NLS-1$
869
                            + firstPage.getSelectedDevice());
870
            cpEntries.add(JavaCore.newContainerEntry(entryPath));
871
872
            if (pageLibrary != null) {
873
                List<IPath> list = pageLibrary.getSelectedLibraries();
874
875
                // Add the JMUnit library, if necessary
876
                if(propertiesPage.isJMUnitEnabled()) {
877
                    String libName = "JMUnit for CLDC 1.1"; //$NON-NLS-1$
878
                    IExternalLibrary jmunitLibrary = ExternalLibraryManager.getInstance().getMidletLibrary(libName);
879
                    if (jmunitLibrary == null) {
880
                        String message = NLS.bind(
881
                                "ExternalLibraryManager does not contain a {0} library.",
882
                                libName);
883
                        MTJStatusHandler.throwCoreException(IStatus.ERROR, -999, message);
884
                    }
885
                    
886
                    IPath path = new Path(ExternalLibraryClasspathContainer.EXTERNAL_LIBRARY_CONTAINER_ID + File.separator + libName);
887
                    list.add(path);
888
                }
889
                
890
                for (IPath path : list) {
891
                    cpEntries.add(JavaCore.newContainerEntry(path, true));
892
                }
893
                    
894
            }
895
896
            entries = cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
897
898
            if (monitor.isCanceled()) {
899
                throw new OperationCanceledException();
900
            }
901
902
            init(javaProject, getOutputLocation(), entries, true);
903
        } finally {
904
            monitor.done();
905
        }
906
    }
907
908
    /**
909
     * Removes the provisional project. The provisional project is typically
910
     * removed when the user cancels the wizard or goes back to the first page.
911
     */
912
    protected void removeProvisonalProject() {
913
        if (!currProject.exists()) {
914
            currProject = null;
915
            return;
916
        }
917
918
        IRunnableWithProgress op = new IRunnableWithProgress() {
919
            public void run(IProgressMonitor monitor)
920
                    throws InvocationTargetException, InterruptedException {
921
                doRemoveProject(monitor);
922
            }
923
        };
924
925
        try {
926
            getContainer().run(true, true,
927
                    new WorkspaceModifyDelegatingOperation(op));
928
        } catch (InvocationTargetException e) {
929
930
            final String title = MTJUIMessages.NewMidletProjectWizardPageThree_updateProject_errordialog_title;
931
            final String message = MTJUIMessages.NewMidletProjectWizardPageThree_updateProject_errordialog_message;
932
            ExceptionHandler.handle(e, getShell(), title, message);
933
934
        } catch (InterruptedException e) {
935
            // cancel pressed
936
        }
937
    }
938
939
    /*
940
     * (non-Javadoc)
941
     * @see
942
     * org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage#useNewSourcePage
943
     * ()
944
     */
945
    @Override
946
    protected final boolean useNewSourcePage() {
947
        return true;
948
    }
949
}
(-)src/org/eclipse/mtj/internal/ui/wizards/dialogfields/ComboButtonDialogField.java (+140 lines)
Line 0 Link Here
1
/**
2
 * Copyright (c) 2009 Motorola.
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
 *     Fernando Rocha (Motorola) - Initial implementation
11
 */
12
package org.eclipse.mtj.internal.ui.wizards.dialogfields;
13
14
import org.eclipse.swt.SWT;
15
import org.eclipse.swt.events.SelectionEvent;
16
import org.eclipse.swt.events.SelectionListener;
17
import org.eclipse.swt.layout.GridData;
18
import org.eclipse.swt.widgets.Button;
19
import org.eclipse.swt.widgets.Combo;
20
import org.eclipse.swt.widgets.Composite;
21
import org.eclipse.swt.widgets.Control;
22
import org.eclipse.swt.widgets.Label;
23
24
/**
25
 * Dialog field containing a label, combo control and a button control.
26
 * 
27
 * @author Fernando Rocha
28
 * @since 1.0
29
 */
30
public class ComboButtonDialogField extends ComboDialogField {
31
32
    protected static GridData gridDataForButton(Button button, int span) {
33
        GridData gd = new GridData();
34
        gd.horizontalAlignment = GridData.FILL;
35
        gd.grabExcessHorizontalSpace = false;
36
        gd.horizontalSpan = span;
37
        return gd;
38
    }
39
40
    private IComboButtonAdapter fComboButtonAdapter;
41
42
    private Button fSelectButton;
43
    private String fSelectButtonLabel;
44
    private boolean fButtonEnabled;
45
46
    public ComboButtonDialogField(IComboButtonAdapter adapter, int comboStyle) {
47
        super(comboStyle);
48
        fComboButtonAdapter = adapter;
49
        fSelectButtonLabel = "!Select...!"; //$NON-NLS-1$
50
        fButtonEnabled = true;
51
    }
52
53
    // ------ adapter communication
54
55
    /**
56
     * Programmatical pressing of the button
57
     */
58
    public void changeControlPressed() {
59
        fComboButtonAdapter.changeControlPressed(this);
60
    }
61
62
    // ------- layout helpers
63
64
    /*
65
     * @see DialogField#doFillIntoGrid
66
     */
67
    @Override
68
    public Control[] doFillIntoGrid(Composite parent, int nColumns) {
69
        assertEnoughColumns(nColumns);
70
71
        Label label = getLabelControl(parent);
72
        label.setLayoutData(gridDataForLabel(1));
73
        Combo combo = getComboControl(parent);
74
        combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // gridDataForCombo(nColumns
75
                                                                     // - 2));
76
        Button button = getChangeControl(parent);
77
        button.setLayoutData(gridDataForButton(button, 1));
78
79
        return new Control[] { label, combo, button };
80
    }
81
82
    /**
83
     * Sets the enable state of the button.
84
     */
85
    public void enableButton(boolean enable) {
86
        if (isOkToUse(fSelectButton)) {
87
            fSelectButton.setEnabled(isEnabled() && enable);
88
        }
89
        fButtonEnabled = enable;
90
    }
91
92
    /**
93
     * Creates or returns the created button widget.
94
     * 
95
     * @param parent The parent composite or <code>null</code> if the widget has
96
     *            already been created.
97
     */
98
    public Button getChangeControl(Composite parent) {
99
        if (fSelectButton == null) {
100
            assertCompositeNotNull(parent);
101
102
            fSelectButton = new Button(parent, SWT.PUSH);
103
            fSelectButton.setFont(parent.getFont());
104
            fSelectButton.setText(fSelectButtonLabel);
105
            fSelectButton.setEnabled(isEnabled() && fButtonEnabled);
106
            fSelectButton.addSelectionListener(new SelectionListener() {
107
                public void widgetDefaultSelected(SelectionEvent e) {
108
                    changeControlPressed();
109
                }
110
111
                public void widgetSelected(SelectionEvent e) {
112
                    changeControlPressed();
113
                }
114
            });
115
116
        }
117
        return fSelectButton;
118
    }
119
120
    /**
121
     * Sets the label of the button.
122
     */
123
    public void setButtonLabel(String label) {
124
        fSelectButtonLabel = label;
125
    }
126
127
    @Override
128
    public int getNumberOfControls() {
129
        return 3;
130
    }
131
132
    @Override
133
    protected void updateEnableState() {
134
        super.updateEnableState();
135
        if (isOkToUse(fSelectButton)) {
136
            fSelectButton.setEnabled(isEnabled() && fButtonEnabled);
137
        }
138
    }
139
140
}
(-)src/org/eclipse/mtj/internal/ui/wizards/dialogfields/IComboButtonAdapter.java (+24 lines)
Line 0 Link Here
1
/**
2
 * Copyright (c) 2009 Motorola.
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
 *     Fernando Rocha (Motorola) - Initial implementation
11
 */
12
package org.eclipse.mtj.internal.ui.wizards.dialogfields;
13
14
/**
15
 * Change listener used by <code>ComboButtonDialogField</code>
16
 * 
17
 * @author Fernando Rocha
18
 * @since 1.0
19
 */
20
public interface IComboButtonAdapter {
21
22
	void changeControlPressed(DialogField field);
23
	
24
}
(-)src/org/eclipse/mtj/internal/ui/messages.properties (-15 / +39 lines)
Lines 727-732 Link Here
727
NewMidletProjectWizardPageOne_locationGroup_externalLocationRadio=Create project from existing source
727
NewMidletProjectWizardPageOne_locationGroup_externalLocationRadio=Create project from existing source
728
NewMidletProjectWizardPageOne_locationGroup_projectLocation=Directory:
728
NewMidletProjectWizardPageOne_locationGroup_projectLocation=Directory:
729
NewMidletProjectWizardPageOne_locationGroup_workspaceLocationRadio=Create new project in workspace
729
NewMidletProjectWizardPageOne_locationGroup_workspaceLocationRadio=Create new project in workspace
730
NewMidletProjectWizardPageOne_locationGroup_workingSetsButton=Add project to working sets
731
NewMidletProjectWizardPageOne_workingSet_null=The Working Set can not be empty
732
NewMidletProjectWizardPageOne_workingSetGroup_contents=Working Sets
733
NewMidletProjectWizardPageOne_workingSetGroup_selection=Working Sets:
734
NewMidletProjectWizardPageOne_workingSetGroup_select_button=Select...
730
NewMidletProjectWizardPageOne_validate_devicecount_error=You must add at least one configuration.
735
NewMidletProjectWizardPageOne_validate_devicecount_error=You must add at least one configuration.
731
NewMidletProjectWizardPageOne_validate_jadname_error_extension=Invalid jad name, missing the \".jad\" file extension.
736
NewMidletProjectWizardPageOne_validate_jadname_error_extension=Invalid jad name, missing the \".jad\" file extension.
732
NewMidletProjectWizardPageOne_validate_jadname_error_emptyname=Invalid jad name, missing the file name.
737
NewMidletProjectWizardPageOne_validate_jadname_error_emptyname=Invalid jad name, missing the file name.
Lines 742-762 Link Here
742
NewMidletProjectWizardPageOne_projectNameGroup_update_error_workspace2=The selected existing source location in the workspace root does not exist
747
NewMidletProjectWizardPageOne_projectNameGroup_update_error_workspace2=The selected existing source location in the workspace root does not exist
743
NewMidletProjectWizardPageOne_title=Create a MIDlet Project
748
NewMidletProjectWizardPageOne_title=Create a MIDlet Project
744
749
745
NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_message=An error occurred while creating project. Check log for details.
750
NewMidletProjectWizardPageTwo_description=Enter the data required to generate the MIDlet Project
746
NewMidletProjectWizardPageTwo_changeToNewProject_errordialog_title=New MIDlet Project
751
NewMidletProjectWizardPageTwo_propertiesGroup_contents=MIDlet Project Properties
747
NewMidletProjectWizardPageTwo_createBackup_error_1=Problem while creating backup for ''
752
NewMidletProjectWizardPageTwo_propertiesGroup_midletName=MIDlet Name
748
NewMidletProjectWizardPageTwo_createBackup_error_2=''
753
NewMidletProjectWizardPageTwo_propertiesGroup_midletVendor=MIDlet Vendor
749
NewMidletProjectWizardPageTwo_doRemoveProject_taskname=Removing project...
754
NewMidletProjectWizardPageTwo_propertiesGroup_midletVersion=MIDlet Version
750
NewMidletProjectWizardPageTwo_performFinish_monitor_taskname=Creating project...
755
NewMidletProjectWizardPageTwo_propertiesGroup_meConfiguration=Microedition Configuration
751
NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_message=An error occurred while creating project. Check log for details.
756
NewMidletProjectWizardPageTwo_propertiesGroup_meProfile=Microedition Profile
752
NewMidletProjectWizardPageTwo_rememberExisitingFolders_errordialog_title=New MIDlet Project
757
NewMidletProjectWizardPageTwo_propertiesGroup_fieldEmpty=The field \"{0}\" is required.
753
NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotclasspath=Problem while restoring backup for .classpath
758
NewMidletProjectWizardPageTwo_optionsGroup_contents=MIDlet Project Options
754
NewMidletProjectWizardPageTwo_restoreExistingFiles_problem_restoring_dotproject=Problem while restoring backup for .project
759
NewMidletProjectWizardPageTwo_optionsGroup_enablePreprocessing=Enable Preprocessing Support
755
NewMidletProjectWizardPageTwo_updateProject_errordialog_message=An error occurred while creating project. Check log for details.
760
NewMidletProjectWizardPageTwo_optionsGroup_enableLocalization=Enable Localization Support
756
NewMidletProjectWizardPageTwo_updateProject_errordialog_title=New MIDlet Project
761
NewMidletProjectWizardPageTwo_optionsGroup_propertiesFolder=Properties Folder:
757
NewMidletProjectWizardPageTwo_updateProject_fail_read_metadata=Could not read project metadata
762
NewMidletProjectWizardPageTwo_optionsGroup_package=Package:
758
NewMidletProjectWizardPageTwo_updateProject_monitor_buildpath_name=Initializing build path
763
NewMidletProjectWizardPageTwo_optionsGroup_packageEmpty=The use of the default package is discouraged.
759
NewMidletProjectWizardPageTwo_updateProject_taskname=Initializing project...
764
NewMidletProjectWizardPageTwo_optionsGroup_packageUpperCase=Discouraged package name. By convention, package names usually start with a lowercase letter.
765
NewMidletProjectWizardPageTwo_optionsGroup_packageError=Invalid package name. \"{0}\" is not a valid Java identifier
766
NewMidletProjectWizardPageTwo_optionsGroup_enableJMUnit=Enable JMUnit Support
767
NewMidletProjectWizardPageTwo_title=MIDlet Project Content
768
769
NewMidletProjectWizardPageThree_changeToNewProject_errordialog_message=An error occurred while creating project. Check log for details.
770
NewMidletProjectWizardPageThree_changeToNewProject_errordialog_title=New MIDlet Project
771
NewMidletProjectWizardPageThree_createBackup_error_1=Problem while creating backup for ''
772
NewMidletProjectWizardPageThree_createBackup_error_2=''
773
NewMidletProjectWizardPageThree_doRemoveProject_taskname=Removing project...
774
NewMidletProjectWizardPageThree_performFinish_monitor_taskname=Creating project...
775
NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_message=An error occurred while creating project. Check log for details.
776
NewMidletProjectWizardPageThree_rememberExisitingFolders_errordialog_title=New MIDlet Project
777
NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotclasspath=Problem while restoring backup for .classpath
778
NewMidletProjectWizardPageThree_restoreExistingFiles_problem_restoring_dotproject=Problem while restoring backup for .project
779
NewMidletProjectWizardPageThree_updateProject_errordialog_message=An error occurred while creating project. Check log for details.
780
NewMidletProjectWizardPageThree_updateProject_errordialog_title=New MIDlet Project
781
NewMidletProjectWizardPageThree_updateProject_fail_read_metadata=Could not read project metadata
782
NewMidletProjectWizardPageThree_updateProject_monitor_buildpath_name=Initializing build path
783
NewMidletProjectWizardPageThree_updateProject_taskname=Initializing project...
760
784
761
NewMidletProjectWizardPageLibrary_title=Select a Library
785
NewMidletProjectWizardPageLibrary_title=Select a Library
762
NewMidletProjectWizardPageLibrary_description=Select the libraries to be included in your project classpath and exported in the deployable JAR file. 
786
NewMidletProjectWizardPageLibrary_description=Select the libraries to be included in your project classpath and exported in the deployable JAR file. 

Return to bug 261873