This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 169620
Collapse All | Expand All

(-)a/settings/apichanges.xml (+13 lines)
Lines 119-124 Link Here
119
        </description>
119
        </description>
120
        <issue number="155962"/>
120
        <issue number="155962"/>
121
    </change>
121
    </change>
122
    <change id="convert.as.javabean">
123
        <api name="settings_spi"/>
124
        <summary>@ConvertAsJavaBean annotation</summary>
125
        <version major="1" minor="20"/>
126
        <date day="7" month="8" year="2009"/>
127
        <author login="jtulach"/>
128
        <compatibility addition="yes" binary="compatible" deletion="no" deprecation="no" modification="yes" semantic="compatible" source="compatible"/>
129
        <description>
130
            Easy way to use JavaBean's archiver for persistence of objects.
131
        </description>
132
        <class package="org.netbeans.api.settings" name="ConvertAsJavaBean"/>
133
        <issue number="169620"/>
134
    </change>
122
    <change id="convertor.propertyannotation">
135
    <change id="convertor.propertyannotation">
123
        <api name="settings_spi"/>
136
        <api name="settings_spi"/>
124
        <summary>@ConvertAsProperties annotation</summary>
137
        <summary>@ConvertAsProperties annotation</summary>
(-)a/settings/nbproject/project.properties (-1 / +1 lines)
Lines 44-47 Link Here
44
javadoc.apichanges=${basedir}/apichanges.xml
44
javadoc.apichanges=${basedir}/apichanges.xml
45
javadoc.arch=${basedir}/arch.xml
45
javadoc.arch=${basedir}/arch.xml
46
javadoc.main.page=org/netbeans/spi/settings/doc-files/api.html
46
javadoc.main.page=org/netbeans/spi/settings/doc-files/api.html
47
spec.version.base=1.19.0
47
spec.version.base=1.20.0
(-)3296fc6624df (+81 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
8
 * Development and Distribution License("CDDL") (collectively, the
9
 * "License"). You may not use this file except in compliance with the
10
 * License. You can obtain a copy of the License at
11
 * http://www.netbeans.org/cddl-gplv2.html
12
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
 * specific language governing permissions and limitations under the
14
 * License.  When distributing the software, include this License Header
15
 * Notice in each file and include the License file at
16
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
17
 * particular file as subject to the "Classpath" exception as provided
18
 * by Sun in the GPL Version 2 section of the License file that
19
 * accompanied this code. If applicable, add the following below the
20
 * License Header, with the fields enclosed by brackets [] replaced by
21
 * your own identifying information:
22
 * "Portions Copyrighted [year] [name of copyright owner]"
23
 *
24
 * Contributor(s):
25
 *
26
 * The Original Software is NetBeans. The Initial Developer of the Original
27
 * Software is Sun Microsystems, Inc. Portions Copyright 2002-2003 Sun
28
 * Microsystems, Inc. All Rights Reserved.
29
 *
30
 * If you wish your version of this file to be governed by only the CDDL
31
 * or only the GPL Version 2, indicate your decision by adding
32
 * "[Contributor] elects to include this software in this distribution
33
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
34
 * single choice of license, a recipient has the option to distribute
35
 * your version of this file under either the CDDL, the GPL Version 2 or
36
 * to extend the choice of license to its licensees as provided above.
37
 * However, if you add GPL Version 2 code and therefore, elected the GPL
38
 * Version 2 license, then the option applies only if the new code is
39
 * made subject to such option by the copyright holder.
40
 */
41
42
package org.netbeans.api.settings;
43
44
import java.beans.PropertyChangeListener;
45
import java.beans.XMLDecoder;
46
import java.beans.XMLEncoder;
47
import java.lang.annotation.Documented;
48
import java.lang.annotation.ElementType;
49
import java.lang.annotation.Retention;
50
import java.lang.annotation.RetentionPolicy;
51
import java.lang.annotation.Target;
52
53
/** Specifies the kind of persistence to use of the annotated class.
54
 * Uses {@link XMLDecoder} and {@link XMLEncoder} to store and read
55
 * values of the class (and by default also its subclasses).
56
 * <p>
57
 * The format uses getters and setters of the bean and usually needs
58
 * default constructor:
59
 * <pre>
60
 * <code>@</code>ConvertAsJavaBean
61
 * <font class="type">public class</font> YourObject {
62
 *   <font class="type">public</font> YourObject() {}
63
 *   <font class="type">public</font> <font class="type">String</font> <font class="function-name">getName</font>();
64
 *   <font class="type">public void</font> <font class="function-name">setName</font>(<font class="type">String</font> <font class="variable-name">name</font>);
65
 * }
66
 * </pre>
67
 * If the bean supports {@link PropertyChangeListener} notifications and
68
 * contains <code>addPropertyChangeListener</code> method, the system
69
 * starts to listen on existing objects and in case a property change
70
 * is delivered, the new state of the object is persisted again.
71
 *
72
 * @author Jaroslav Tulach <jtulach@netbeans.org>
73
 * @since 1.20
74
 */
75
@Retention(RetentionPolicy.SOURCE)
76
@Target(ElementType.TYPE)
77
@Documented
78
public @interface ConvertAsJavaBean {
79
    /** Shall subclasses of this class be also converted as JavaBeans? */
80
    boolean subclasses() default true;
81
}
(-)a/settings/src/org/netbeans/modules/settings/convertors/ConvertorProcessor.java (-7 / +24 lines)
Lines 54-60 Link Here
54
import javax.lang.model.type.TypeKind;
54
import javax.lang.model.type.TypeKind;
55
import javax.lang.model.type.TypeMirror;
55
import javax.lang.model.type.TypeMirror;
56
import javax.lang.model.util.ElementFilter;
56
import javax.lang.model.util.ElementFilter;
57
import org.netbeans.api.settings.ConvertAsJavaBean;
57
import org.netbeans.api.settings.ConvertAsProperties;
58
import org.netbeans.api.settings.ConvertAsProperties;
59
import org.netbeans.modules.settings.Env;
58
import org.openide.filesystems.annotations.LayerBuilder.File;
60
import org.openide.filesystems.annotations.LayerBuilder.File;
59
import org.openide.filesystems.annotations.LayerGeneratingProcessor;
61
import org.openide.filesystems.annotations.LayerGeneratingProcessor;
60
import org.openide.filesystems.annotations.LayerGenerationException;
62
import org.openide.filesystems.annotations.LayerGenerationException;
Lines 66-72 Link Here
66
 */
68
 */
67
@ServiceProvider(service=Processor.class)
69
@ServiceProvider(service=Processor.class)
68
@SupportedSourceVersion(SourceVersion.RELEASE_6)
70
@SupportedSourceVersion(SourceVersion.RELEASE_6)
69
@SupportedAnnotationTypes("org.netbeans.api.settings.ConvertAsProperties")//NOI18N
71
@SupportedAnnotationTypes({
72
    "org.netbeans.api.settings.ConvertAsProperties", //NOI18N
73
    "org.netbeans.api.settings.ConvertAsJavaBean" //NOI18N
74
})
70
public class ConvertorProcessor extends LayerGeneratingProcessor {
75
public class ConvertorProcessor extends LayerGeneratingProcessor {
71
76
72
77
Lines 82-88 Link Here
82
        for (Element e : env.getElementsAnnotatedWith(ConvertAsProperties.class)) {
87
        for (Element e : env.getElementsAnnotatedWith(ConvertAsProperties.class)) {
83
            ConvertAsProperties reg = e.getAnnotation(ConvertAsProperties.class);
88
            ConvertAsProperties reg = e.getAnnotation(ConvertAsProperties.class);
84
89
85
            String convElem = instantiableClassOrMethod(e);
90
            String convElem = instantiableClassOrMethod(e, true);
86
            final String dtd = reg.dtd();
91
            final String dtd = reg.dtd();
87
92
88
            String dtdCode = convertPublicId(dtd);
93
            String dtdCode = convertPublicId(dtd);
Lines 131-136 Link Here
131
                boolvalue("xmlproperties.preventStoring", !reg.autostore());
136
                boolvalue("xmlproperties.preventStoring", !reg.autostore());
132
            commaSeparated(f, reg.ignoreChanges()).write();
137
            commaSeparated(f, reg.ignoreChanges()).write();
133
        }
138
        }
139
140
141
        for (Element e : env.getElementsAnnotatedWith(ConvertAsJavaBean.class)) {
142
            ConvertAsJavaBean reg = e.getAnnotation(ConvertAsJavaBean.class);
143
            String convElem = instantiableClassOrMethod(e, false);
144
            File f = layer(e).file("xml/memory/" + convElem.replace('.', '/'));
145
            f.stringvalue("settings.providerPath", "xml/lookups/NetBeans/DTD_XML_beans_1_0.instance");
146
            if (reg.subclasses()) {
147
                f.boolvalue(Env.EA_SUBCLASSES, true);
148
            }
149
            f.write();
150
        }
134
        return true;
151
        return true;
135
    }
152
    }
136
153
Lines 205-211 Link Here
205
        return f.stringvalue("xmlproperties.ignoreChanges", sb.toString());
222
        return f.stringvalue("xmlproperties.ignoreChanges", sb.toString());
206
    }
223
    }
207
224
208
    private String instantiableClassOrMethod(Element e) throws IllegalArgumentException, LayerGenerationException {
225
    private String instantiableClassOrMethod(Element e, boolean checkMethods) throws IllegalArgumentException, LayerGenerationException {
209
        switch (e.getKind()) {
226
        switch (e.getKind()) {
210
            case CLASS: {
227
            case CLASS: {
211
                String clazz = processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString();
228
                String clazz = processingEnv.getElementUtils().getBinaryName((TypeElement) e).toString();
Lines 224-232 Link Here
224
                        throw new LayerGenerationException(clazz + " must have a no-argument constructor", e);
241
                        throw new LayerGenerationException(clazz + " must have a no-argument constructor", e);
225
                    }
242
                    }
226
                }
243
                }
227
                TypeMirror propType;
244
                if (checkMethods) {
228
                propType = processingEnv.getElementUtils().getTypeElement("java.util.Properties").asType();
245
                    TypeMirror propType;
229
                {
246
                    propType = processingEnv.getElementUtils().getTypeElement("java.util.Properties").asType();
230
                    boolean hasRead = false;
247
                    boolean hasRead = false;
231
                    boolean hasWrite = false;
248
                    boolean hasWrite = false;
232
                    for (ExecutableElement m : ElementFilter.methodsIn(e.getEnclosedElements())) {
249
                    for (ExecutableElement m : ElementFilter.methodsIn(e.getEnclosedElements())) {
Lines 256-262 Link Here
256
                return clazz;
273
                return clazz;
257
            }
274
            }
258
            default:
275
            default:
259
                throw new IllegalArgumentException("Annotated element is not loadable as an instance: " + e);
276
                throw new LayerGenerationException("Annotated element is not loadable as an instance: " + e);
260
        }
277
        }
261
    }
278
    }
262
}
279
}
(-)3296fc6624df (+179 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
8
 * Development and Distribution License("CDDL") (collectively, the
9
 * "License"). You may not use this file except in compliance with the
10
 * License. You can obtain a copy of the License at
11
 * http://www.netbeans.org/cddl-gplv2.html
12
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
 * specific language governing permissions and limitations under the
14
 * License.  When distributing the software, include this License Header
15
 * Notice in each file and include the License file at
16
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
17
 * particular file as subject to the "Classpath" exception as provided
18
 * by Sun in the GPL Version 2 section of the License file that
19
 * accompanied this code. If applicable, add the following below the
20
 * License Header, with the fields enclosed by brackets [] replaced by
21
 * your own identifying information:
22
 * "Portions Copyrighted [year] [name of copyright owner]"
23
 *
24
 * Contributor(s):
25
 *
26
 * The Original Software is NetBeans. The Initial Developer of the Original
27
 * Software is Sun Microsystems, Inc. Portions Copyright 2002-2003 Sun
28
 * Microsystems, Inc. All Rights Reserved.
29
 *
30
 * If you wish your version of this file to be governed by only the CDDL
31
 * or only the GPL Version 2, indicate your decision by adding
32
 * "[Contributor] elects to include this software in this distribution
33
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
34
 * single choice of license, a recipient has the option to distribute
35
 * your version of this file under either the CDDL, the GPL Version 2 or
36
 * to extend the choice of license to its licensees as provided above.
37
 * However, if you add GPL Version 2 code and therefore, elected the GPL
38
 * Version 2 license, then the option applies only if the new code is
39
 * made subject to such option by the copyright holder.
40
 */
41
42
package org.netbeans.modules.settings.convertors;
43
44
import java.beans.PropertyChangeListener;
45
import java.beans.XMLDecoder;
46
import java.beans.XMLEncoder;
47
import java.io.BufferedReader;
48
import java.io.ByteArrayOutputStream;
49
import java.io.IOException;
50
import java.nio.CharBuffer;
51
import java.util.logging.Level;
52
import java.util.logging.Logger;
53
54
import java.util.regex.Matcher;
55
import java.util.regex.Pattern;
56
57
58
import org.netbeans.spi.settings.Convertor;
59
import org.netbeans.spi.settings.Saver;
60
61
import org.openide.util.Exceptions;
62
import org.openide.util.io.ReaderInputStream;
63
64
/** Convertor using {@link  java.beans.XMLEncoder} and
65
 * {@link  java.beans.XMLDecoder}.
66
 *
67
 * @author  Jaroslav Tulach
68
 */
69
public final class XMLBeanConvertor extends Convertor implements PropertyChangeListener {
70
    /** create convertor instance; should be used in module layers
71
     * @param providerFO provider file object
72
     */
73
    public static Convertor create() {
74
        return new XMLBeanConvertor();
75
    }
76
    
77
    public XMLBeanConvertor() {
78
    }
79
    
80
    public Object read(java.io.Reader r) throws IOException, ClassNotFoundException {
81
        java.io.
82
        BufferedReader buf = new BufferedReader(r, 4096);
83
        CharBuffer arr = CharBuffer.allocate(2048);
84
        buf.mark(arr.capacity());
85
        buf.read(arr);
86
        arr.flip();
87
88
        Matcher m = Pattern.compile("<java").matcher(arr);
89
        if (m.find()) {
90
            buf.reset();
91
            buf.skip(m.start());
92
        } else {
93
            buf.reset();
94
        }
95
        XMLDecoder d = new XMLDecoder(new ReaderInputStream(buf, "UTF-8"));
96
        return d.readObject();
97
    }
98
    
99
    public void write(java.io.Writer w, Object inst) throws IOException {
100
        ByteArrayOutputStream out = new ByteArrayOutputStream();
101
        XMLEncoder e = new XMLEncoder(out);
102
        e.writeObject(inst);
103
        e.close();
104
        String data = new String(out.toByteArray(), "UTF-8");
105
        data = data.replaceFirst("<java", "<!DOCTYPE xmlbeans PUBLIC \"-//NetBeans//DTD XML beans 1.0//EN\" \"http://www.netbeans.org/dtds/xml-beans-1_0.dtd\">\n<java");
106
        w.write(data);
107
    }
108
    
109
    /** an object listening on the setting changes */
110
    private Saver saver;
111
    public void registerSaver(Object inst, Saver s) {
112
        if (saver != null) {
113
            XMLSettingsSupport.err.warning("[Warning] Saver already registered");
114
            return;
115
        }
116
        
117
        // add propertyChangeListener
118
        try {
119
            java.lang.reflect.Method method = inst.getClass().getMethod(
120
                "addPropertyChangeListener", // NOI18N
121
                new Class[] {PropertyChangeListener.class});
122
            method.invoke(inst, new Object[] {this});
123
            this.saver = s;
124
        } catch (NoSuchMethodException ex) {
125
            XMLSettingsSupport.err.warning(
126
            "ObjectChangesNotifier: NoSuchMethodException: " + // NOI18N
127
            inst.getClass().getName() + ".addPropertyChangeListener"); // NOI18N
128
        } catch (IllegalAccessException ex) {
129
            Exceptions.printStackTrace(ex);
130
        } catch (java.lang.reflect.InvocationTargetException ex) {
131
            Exceptions.printStackTrace(ex);
132
        }
133
    }
134
    
135
    public void unregisterSaver(Object inst, Saver s) {
136
        if (saver == null) return;
137
        if (saver != s) {
138
            XMLSettingsSupport.err.warning("[Warning] trying unregistered unknown Saver");
139
            return;
140
        }
141
        try {
142
            java.lang.reflect.Method method = inst.getClass().getMethod(
143
                "removePropertyChangeListener", // NOI18N
144
                new Class[] {PropertyChangeListener.class});
145
            method.invoke(inst, new Object[] {this});
146
            this.saver = null;
147
        } catch (NoSuchMethodException ex) {
148
            XMLSettingsSupport.err.fine(
149
            "ObjectChangesNotifier: NoSuchMethodException: " + // NOI18N
150
            inst.getClass().getName() + ".removePropertyChangeListener"); // NOI18N
151
            // just changes done through gui will be saved
152
        } catch (IllegalAccessException ex) {
153
            Exceptions.printStackTrace(ex);
154
            // just changes done through gui will be saved
155
        } catch (java.lang.reflect.InvocationTargetException ex) {
156
            Exceptions.printStackTrace(ex);
157
            // just changes done through gui will be saved
158
        }
159
    }
160
    
161
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
162
        if (saver == null) {
163
            return;
164
        }
165
        if (acceptSave()) {
166
            try {
167
                saver.requestSave();
168
            } catch (IOException ex) {
169
                Logger.getLogger(XMLBeanConvertor.class.getName()).log(Level.WARNING, null, ex);
170
            }
171
        } else {
172
            saver.markDirty();
173
        }
174
    }
175
    
176
    private boolean acceptSave() {
177
        return true;
178
    }
179
}
(-)a/settings/src/org/netbeans/modules/settings/convertors/XMLSettingsSupport.java (-1 / +1 lines)
Lines 432-438 Link Here
432
        
432
        
433
        public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
433
        public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
434
        throws SAXException {
434
        throws SAXException {
435
            if (INSTANCE_DTD_ID.equals (publicId)) {
435
            if (INSTANCE_DTD_ID.equals (publicId) || "-//NetBeans//DTD XML beans 1.0//EN".equals(publicId)) {
436
                return new org.xml.sax.InputSource (new ByteArrayInputStream (new byte[0]));
436
                return new org.xml.sax.InputSource (new ByteArrayInputStream (new byte[0]));
437
            } else {
437
            } else {
438
                return null; // i.e. follow advice of systemID
438
                return null; // i.e. follow advice of systemID
(-)3296fc6624df (+152 lines)
Added Link Here
1
<?xml encoding="UTF-8" ?>
2
<!--
3
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
5
Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
6
7
8
The contents of this file are subject to the terms of either the GNU
9
General Public License Version 2 only ("GPL") or the Common
10
Development and Distribution License("CDDL") (collectively, the
11
"License"). You may not use this file except in compliance with the
12
License. You can obtain a copy of the License at
13
http://www.netbeans.org/cddl-gplv2.html
14
or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
15
specific language governing permissions and limitations under the
16
License.  When distributing the software, include this License Header
17
Notice in each file and include the License file at
18
nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
19
particular file as subject to the "Classpath" exception as provided
20
by Sun in the GPL Version 2 section of the License file that
21
accompanied this code. If applicable, add the following below the
22
License Header, with the fields enclosed by brackets [] replaced by
23
your own identifying information:
24
"Portions Copyrighted [year] [name of copyright owner]"
25
26
Contributor(s):
27
28
The Original Software is NetBeans. The Initial Developer of the Original
29
Software is Sun Microsystems, Inc. Portions Copyright 2002 Sun
30
Microsystems, Inc. All Rights Reserved.
31
32
If you wish your version of this file to be governed by only the CDDL
33
or only the GPL Version 2, indicate your decision by adding
34
"[Contributor] elects to include this software in this distribution
35
under the [CDDL or GPL Version 2] license." If you do not indicate a
36
single choice of license, a recipient has the option to distribute
37
your version of this file under either the CDDL, the GPL Version 2 or
38
to extend the choice of license to its licensees as provided above.
39
However, if you add GPL Version 2 code and therefore, elected the GPL
40
Version 2 license, then the option applies only if the new code is
41
made subject to such option by the copyright holder.
42
-->
43
44
<!ELEMENT java (
45
    object   | 
46
    void     | 
47
    string   |  
48
    class    | 
49
    null     | 
50
    array    | 
51
    boolean  | 
52
    byte     | 
53
    char     | 
54
    short    | 
55
    int      | 
56
    long     | 
57
    float    |  
58
    double
59
)*>
60
<!ATTLIST java 
61
    version  CDATA  #IMPLIED
62
    class    CDATA  #IMPLIED
63
>
64
65
<!ELEMENT boolean (#PCDATA)>
66
<!ELEMENT byte    (#PCDATA)>
67
<!ELEMENT char    (#PCDATA)>
68
<!ELEMENT short   (#PCDATA)>
69
<!ELEMENT int     (#PCDATA)>
70
<!ELEMENT long    (#PCDATA)>
71
<!ELEMENT float   (#PCDATA)>
72
<!ELEMENT double  (#PCDATA)>
73
74
<!ELEMENT string  (#PCDATA)>
75
<!ELEMENT class   (#PCDATA)>
76
<!ELEMENT null    (#PCDATA)>
77
78
<!ELEMENT object (
79
    object   | 
80
    void     | 
81
    string   |  
82
    class    | 
83
    null     | 
84
    array    | 
85
    boolean  | 
86
    byte     | 
87
    char     | 
88
    short    | 
89
    int      | 
90
    long     | 
91
    float    |  
92
    double
93
)*>
94
<!ATTLIST object 
95
    id       ID     #IMPLIED
96
    idref    IDREF  #IMPLIED
97
    class    CDATA  #IMPLIED
98
    field    CDATA  #IMPLIED
99
    method   CDATA  #IMPLIED
100
    property CDATA  #IMPLIED
101
    index    CDATA  #IMPLIED
102
>
103
104
<!ELEMENT array (
105
    object   | 
106
    void     | 
107
    string   |  
108
    class    | 
109
    null     | 
110
    array    | 
111
    boolean  | 
112
    byte     | 
113
    char     | 
114
    short    | 
115
    int      | 
116
    long     | 
117
    float    |  
118
    double
119
)*>
120
<!ATTLIST array 
121
    id       ID     #IMPLIED
122
    class    CDATA  #IMPLIED
123
    length   CDATA  #IMPLIED
124
>
125
126
<!ELEMENT void (
127
    object   | 
128
    void     | 
129
    string   |  
130
    class    | 
131
    null     | 
132
    array    | 
133
    boolean  | 
134
    byte     | 
135
    char     | 
136
    short    | 
137
    int      | 
138
    long     | 
139
    float    |  
140
    double
141
)*>
142
<!ATTLIST void 
143
    id       ID     #IMPLIED
144
    class    CDATA  #IMPLIED
145
    method   CDATA  #IMPLIED
146
    property CDATA  #IMPLIED
147
    index    CDATA  #IMPLIED
148
>
149
150
151
152
(-)a/settings/src/org/netbeans/modules/settings/resources/mf-layer.xml (+9 lines)
Lines 50-55 Link Here
50
                    <attr name="instanceCreate" methodvalue="org.netbeans.modules.settings.convertors.SerialDataConvertor$Provider.create"/>
50
                    <attr name="instanceCreate" methodvalue="org.netbeans.modules.settings.convertors.SerialDataConvertor$Provider.create"/>
51
                    <attr name="settings.convertor" newvalue="org.netbeans.modules.settings.convertors.XMLSettingsSupport$Convertor"/>
51
                    <attr name="settings.convertor" newvalue="org.netbeans.modules.settings.convertors.XMLSettingsSupport$Convertor"/>
52
              </file>
52
              </file>
53
            	<!-- Convertor handling XML beans -->
54
                <file name="DTD_XML_beans_1_0.instance">
55
                    <attr name="instanceCreate" methodvalue="org.netbeans.api.settings.Factory.create"/>
56
                    <attr name="settings.convertor" methodvalue="org.netbeans.modules.settings.convertors.XMLBeanConvertor.create"/>
57
                    <attr name="hint.originalPublicID" stringvalue="-//NetBeans//DTD XML beans 1.0//EN"/>
58
              </file>
53
            </folder>
59
            </folder>
54
        </folder>
60
        </folder>
55
        <!-- registered convertors used by InstanceDataObject.create -->
61
        <!-- registered convertors used by InstanceDataObject.create -->
Lines 68-73 Link Here
68
            	<file name="DTD_Session_settings_1_0" url="sessionsettings-1_0.dtd">
74
            	<file name="DTD_Session_settings_1_0" url="sessionsettings-1_0.dtd">
69
                    <attr name="hint.originalPublicID" stringvalue="-//NetBeans//DTD Session settings 1.0//EN"/>
75
                    <attr name="hint.originalPublicID" stringvalue="-//NetBeans//DTD Session settings 1.0//EN"/>
70
            	</file>
76
            	</file>
77
            	<file name="DTD_XML_beans_1_0" url="javabeans-1_0.dtd">
78
                    <attr name="hint.originalPublicID" stringvalue="-//NetBeans//DTD XML beans 1.0//EN"/>
79
            	</file>
71
            </folder>
80
            </folder>
72
        </folder>
81
        </folder>
73
    </folder>
82
    </folder>
(-)3296fc6624df (+226 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
8
 * Development and Distribution License("CDDL") (collectively, the
9
 * "License"). You may not use this file except in compliance with the
10
 * License. You can obtain a copy of the License at
11
 * http://www.netbeans.org/cddl-gplv2.html
12
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
 * specific language governing permissions and limitations under the
14
 * License.  When distributing the software, include this License Header
15
 * Notice in each file and include the License file at
16
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
17
 * particular file as subject to the "Classpath" exception as provided
18
 * by Sun in the GPL Version 2 section of the License file that
19
 * accompanied this code. If applicable, add the following below the
20
 * License Header, with the fields enclosed by brackets [] replaced by
21
 * your own identifying information:
22
 * "Portions Copyrighted [year] [name of copyright owner]"
23
 *
24
 * Contributor(s):
25
 *
26
 * The Original Software is NetBeans. The Initial Developer of the Original
27
 * Software is Sun Microsystems, Inc. Portions Copyright 2002 Sun
28
 * Microsystems, Inc. All Rights Reserved.
29
 *
30
 * If you wish your version of this file to be governed by only the CDDL
31
 * or only the GPL Version 2, indicate your decision by adding
32
 * "[Contributor] elects to include this software in this distribution
33
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
34
 * single choice of license, a recipient has the option to distribute
35
 * your version of this file under either the CDDL, the GPL Version 2 or
36
 * to extend the choice of license to its licensees as provided above.
37
 * However, if you add GPL Version 2 code and therefore, elected the GPL
38
 * Version 2 license, then the option applies only if the new code is
39
 * made subject to such option by the copyright holder.
40
 */
41
42
package org.netbeans.modules.settings.convertors;
43
44
import java.io.*;
45
46
import org.netbeans.api.settings.ConvertAsJavaBean;
47
import org.netbeans.junit.NbTestCase;
48
49
50
51
import org.openide.cookies.InstanceCookie;
52
import org.openide.filesystems.FileObject;
53
import org.openide.filesystems.FileUtil;
54
import org.openide.loaders.DataFolder;
55
import org.openide.loaders.DataObject;
56
import org.openide.loaders.InstanceDataObject;
57
import org.openide.modules.ModuleInfo;
58
import org.openide.util.Lookup;
59
import org.openide.util.test.AnnotationProcessorTestUtils;
60
61
/** Checks usage of annotation to assign XML properties convertor.
62
 *
63
 * @author Jaroslav Tulach
64
 */
65
public final class ConvertAsBeanTest extends NbTestCase {
66
    /** Creates a new instance of XMLPropertiesConvertorTest */
67
    public ConvertAsBeanTest(String name) {
68
        super(name);
69
    }
70
71
    @Override
72
    protected void setUp() throws Exception {
73
        clearWorkDir();
74
        Lookup.getDefault().lookup(ModuleInfo.class);
75
    }
76
    
77
    public void testReadWrite() throws Exception {
78
        AnnoFoo foo = new AnnoFoo();
79
        foo.setName("xxx");
80
81
        DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
82
        DataObject obj = InstanceDataObject.create(test, null, foo, null);
83
        final FileObject pf = obj.getPrimaryFile();
84
        final String content = pf.asText();
85
        if (content.indexOf("<string>xxx</string>") == -1) {
86
            fail(content);
87
        }
88
        obj.setValid(false);
89
        DataObject newObj = DataObject.find(pf);
90
        if (newObj == obj) {
91
            fail("Strange, objects shall differ");
92
        }
93
        InstanceCookie ic = newObj.getLookup().lookup(InstanceCookie.class);
94
        assertNotNull("Instance cookie found", ic);
95
96
        Object read = ic.instanceCreate();
97
        assertNotNull("Instance created", read);
98
        assertEquals("Correct class", AnnoFoo.class, read.getClass());
99
        AnnoFoo readFoo = (AnnoFoo)read;
100
        assertEquals("property changed", "xxx", readFoo.getName());
101
    }
102
103
    public void testReadWriteOnSubclass() throws Exception {
104
        HooFoo foo = new HooFoo();
105
        foo.setName("xxx");
106
107
        DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
108
        DataObject obj = InstanceDataObject.create(test, null, foo, null);
109
        final FileObject pf = obj.getPrimaryFile();
110
        final String content = pf.asText();
111
        if (content.indexOf("<string>xxx</string>") == -1) {
112
            fail(content);
113
        }
114
        obj.setValid(false);
115
        DataObject newObj = DataObject.find(pf);
116
        if (newObj == obj) {
117
            fail("Strange, objects shall differ");
118
        }
119
        InstanceCookie ic = newObj.getLookup().lookup(InstanceCookie.class);
120
        assertNotNull("Instance cookie found", ic);
121
122
        Object read = ic.instanceCreate();
123
        assertNotNull("Instance created", read);
124
        assertEquals("Correct class", HooFoo.class, read.getClass());
125
        HooFoo readFoo = (HooFoo)read;
126
        assertEquals("property changed", "xxx", readFoo.getName());
127
    }
128
129
    @ConvertAsJavaBean(
130
    )
131
    public static class AnnoFoo extends Object {
132
        private String name;
133
134
        public String getName() {
135
            return name;
136
        }
137
138
        public void setName(String name) {
139
            this.name = name;
140
        }
141
    } // end of AnnoFoo
142
143
    public static class HooFoo extends AnnoFoo {
144
        private int count;
145
146
        public int getCount() {
147
            return count;
148
        }
149
150
        public void setCount(int count) {
151
            this.count = count;
152
        }
153
    } // end of HooFoo
154
155
    @ConvertAsJavaBean(
156
        subclasses=false
157
    )
158
    public static class JuuFoo extends Object {
159
        private String name;
160
161
        public String getName() {
162
            return name;
163
        }
164
165
        public void setName(String name) {
166
            this.name = name;
167
        }
168
    } // end of JuuFoo
169
170
    public static class NotFoo extends JuuFoo {
171
        private int count;
172
173
        public int getCount() {
174
            return count;
175
        }
176
177
        public void setCount(int count) {
178
            this.count = count;
179
        }
180
    } // end of NotFoo
181
    public void testReadWriteNotForSubclasses() throws Exception {
182
        NotFoo foo = new NotFoo();
183
        foo.setName("xxx");
184
185
        DataFolder test = DataFolder.findFolder(FileUtil.getConfigRoot());
186
        try {
187
            DataObject obj = InstanceDataObject.create(test, null, foo, null);
188
            final FileObject pf = obj.getPrimaryFile();
189
            final String content = pf.asText();
190
            fail(content);
191
        } catch (NotSerializableException ex) {
192
            // OK
193
        }
194
    }
195
196
    public void testVerifyHaveDefaultConstructor() throws Exception {
197
        AnnotationProcessorTestUtils.makeSource(getWorkDir(), "x.y.Kuk",
198
            "import org.netbeans.api.settings.ConvertAsJavaBean;\n" +
199
            "@ConvertAsJavaBean()\n" +
200
            "public class Kuk {\n" +
201
            "  public Kuk(int i) {}\n" +
202
            "}\n"
203
        );
204
        ByteArrayOutputStream err = new ByteArrayOutputStream();
205
        boolean res = AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, err);
206
        assertFalse("Should fail", res);
207
        if (err.toString().indexOf("x.y.Kuk must have a no-argument constructor") == -1) {
208
            fail("Wrong error message:\n" + err.toString());
209
        }
210
    }
211
    public void testInterfacesCannotBeAnnotated() throws Exception {
212
        AnnotationProcessorTestUtils.makeSource(getWorkDir(), "x.y.Kuk",
213
            "import org.netbeans.api.settings.ConvertAsJavaBean;\n" +
214
            "@ConvertAsJavaBean()\n" +
215
            "public interface Kuk {\n" +
216
            "  public int buk(int i);\n" +
217
            "}\n"
218
        );
219
        ByteArrayOutputStream err = new ByteArrayOutputStream();
220
        boolean res = AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, err);
221
        assertFalse("Should fail", res);
222
        if (err.toString().indexOf("is not loadable") == -1) {
223
            fail("Wrong error message:\n" + err.toString());
224
        }
225
    }
226
}

Return to bug 169620