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

Return to bug 261873