001/**
002 *
003 * Copyright 2003-2007 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.jivesoftware.smackx.xdata.packet;
019
020import org.jivesoftware.smack.packet.Element;
021import org.jivesoftware.smack.packet.Stanza;
022import org.jivesoftware.smack.packet.ExtensionElement;
023import org.jivesoftware.smack.util.XmlStringBuilder;
024import org.jivesoftware.smackx.xdata.FormField;
025
026import java.util.ArrayList;
027import java.util.Collections;
028import java.util.List;
029import java.util.Locale;
030
031/**
032 * Represents a form that could be use for gathering data as well as for reporting data
033 * returned from a search.
034 *
035 * @author Gaston Dombiak
036 */
037public class DataForm implements ExtensionElement {
038
039    public static final String NAMESPACE = "jabber:x:data";
040    public static final String ELEMENT = "x";
041
042    public enum Type {
043        /**
044         * This stanza(/packet) contains a form to fill out. Display it to the user (if your program can).
045         */
046        form,
047
048        /**
049         * The form is filled out, and this is the data that is being returned from the form.
050         */
051        submit,
052
053        /**
054         * The form was cancelled. Tell the asker that piece of information.
055         */
056        cancel,
057
058        /**
059         * Data results being returned from a search, or some other query.
060         */
061        result,
062        ;
063
064        public static Type fromString(String string) {
065            return Type.valueOf(string.toLowerCase(Locale.US));
066        }
067    }
068
069    private Type type;
070    private String title;
071    private List<String> instructions = new ArrayList<String>();
072    private ReportedData reportedData;
073    private final List<Item> items = new ArrayList<Item>();
074    private final List<FormField> fields = new ArrayList<FormField>();
075    private final List<Element> extensionElements = new ArrayList<Element>();
076    
077    public DataForm(Type type) {
078        this.type = type;
079    }
080    
081    /**
082     * Returns the meaning of the data within the context. The data could be part of a form
083     * to fill out, a form submission or data results.
084     * 
085     * @return the form's type.
086     */
087    public Type getType() {
088        return type; 
089    }
090    
091    /**
092     * Returns the description of the data. It is similar to the title on a web page or an X 
093     * window.  You can put a <title/> on either a form to fill out, or a set of data results.
094     * 
095     * @return description of the data.
096     */
097    public String getTitle() {
098        return title;
099    }
100
101    /**
102     * Returns a List of the list of instructions that explain how to fill out the form and 
103     * what the form is about. The dataform could include multiple instructions since each 
104     * instruction could not contain newlines characters. Join the instructions together in order 
105     * to show them to the user.
106     * 
107     * @return a List of the list of instructions that explain how to fill out the form.
108     */
109    public List<String> getInstructions() {
110        synchronized (instructions) {
111            return Collections.unmodifiableList(new ArrayList<String>(instructions));
112        }
113    }
114
115    /**
116     * Returns the fields that will be returned from a search.
117     * 
118     * @return fields that will be returned from a search.
119     */
120    public ReportedData getReportedData() {
121        return reportedData;
122    }
123
124    /**
125     * Returns a List of the items returned from a search.
126     *
127     * @return a List of the items returned from a search.
128     */
129    public List<Item> getItems() {
130        synchronized (items) {
131            return Collections.unmodifiableList(new ArrayList<Item>(items));
132        }
133    }
134
135    /**
136     * Returns a List of the fields that are part of the form.
137     *
138     * @return a List of the fields that are part of the form.
139     */
140    public List<FormField> getFields() {
141        synchronized (fields) {
142            return Collections.unmodifiableList(new ArrayList<FormField>(fields));
143        }
144    }
145
146    /**
147     * Return the form field with the given variable name or null.
148     *
149     * @param variableName
150     * @return the form field or null.
151     * @since 4.1
152     */
153    public FormField getField(String variableName) {
154        synchronized (fields) {
155            for (FormField field : fields) {
156                if (variableName.equals(field.getVariable())) {
157                    return field;
158                }
159            }
160        }
161        return null;
162    }
163
164    public String getElementName() {
165        return ELEMENT;
166    }
167
168    public String getNamespace() {
169        return NAMESPACE;
170    }
171
172    /**
173     * Sets the description of the data. It is similar to the title on a web page or an X window.
174     * You can put a <title/> on either a form to fill out, or a set of data results.
175     * 
176     * @param title description of the data.
177     */
178    public void setTitle(String title) {
179        this.title = title;
180    }
181
182    /**
183     * Sets the list of instructions that explain how to fill out the form and what the form is 
184     * about. The dataform could include multiple instructions since each instruction could not 
185     * contain newlines characters. 
186     * 
187     * @param instructions list of instructions that explain how to fill out the form.
188     */
189    public void setInstructions(List<String> instructions) {
190        this.instructions = instructions;
191    }
192
193    /**
194     * Sets the fields that will be returned from a search.
195     * 
196     * @param reportedData the fields that will be returned from a search.
197     */
198    public void setReportedData(ReportedData reportedData) {
199        this.reportedData = reportedData;
200    }
201
202    /**
203     * Adds a new field as part of the form.
204     * 
205     * @param field the field to add to the form.
206     */
207    public void addField(FormField field) {
208        String fieldVariableName = field.getVariable();
209        if (fieldVariableName != null && getField(fieldVariableName) != null) {
210            throw new IllegalArgumentException("This data form already contains a form field with the variable name '"
211                            + fieldVariableName + "'");
212        }
213        synchronized (fields) {
214            fields.add(field);
215        }
216    }
217    
218    /**
219     * Adds a new instruction to the list of instructions that explain how to fill out the form 
220     * and what the form is about. The dataform could include multiple instructions since each 
221     * instruction could not contain newlines characters. 
222     * 
223     * @param instruction the new instruction that explain how to fill out the form.
224     */
225    public void addInstruction(String instruction) {
226        synchronized (instructions) {
227            instructions.add(instruction);
228        }
229    }
230
231    /**
232     * Adds a new item returned from a search.
233     * 
234     * @param item the item returned from a search.
235     */
236    public void addItem(Item item) {
237        synchronized (items) {
238            items.add(item);
239        }
240    }
241
242    public void addExtensionElement(Element element) {
243        extensionElements.add(element);
244    }
245
246    public List<Element> getExtensionElements() {
247        return Collections.unmodifiableList(extensionElements);
248    }
249
250    /**
251     * Returns the hidden FORM_TYPE field or null if this data form has none.
252     *
253     * @return the hidden FORM_TYPE field or null.
254     * @since 4.1
255     */
256    public FormField getHiddenFormTypeField() {
257        FormField field = getField(FormField.FORM_TYPE);
258        if (field != null && field.getType() == FormField.Type.hidden) {
259            return field;
260        }
261        return null;
262    }
263
264    /**
265     * Returns true if this DataForm has at least one FORM_TYPE field which is
266     * hidden. This method is used for sanity checks.
267     *
268     * @return true if there is at least one field which is hidden.
269     */
270    public boolean hasHiddenFormTypeField() {
271        return getHiddenFormTypeField() != null;
272    }
273
274    @Override
275    public XmlStringBuilder toXML() {
276        XmlStringBuilder buf = new XmlStringBuilder(this);
277        buf.attribute("type", getType());
278        buf.rightAngleBracket();
279
280        buf.optElement("title", getTitle());
281        for (String instruction : getInstructions()) {
282            buf.element("instructions", instruction);
283        }
284        // Append the list of fields returned from a search
285        if (getReportedData() != null) {
286            buf.append(getReportedData().toXML());
287        }
288        // Loop through all the items returned from a search and append them to the string buffer
289        for (Item item : getItems()) {
290            buf.append(item.toXML());
291        }
292        // Loop through all the form fields and append them to the string buffer
293        for (FormField field : getFields()) {
294            buf.append(field.toXML());
295        }
296        for (Element element : extensionElements) {
297            buf.append(element.toXML());
298        }
299        buf.closeElement(this);
300        return buf;
301    }
302
303    /**
304     * 
305     * @param packet
306     * @return the DataForm or null
307     */
308    public static DataForm from(Stanza packet) {
309        return (DataForm) packet.getExtension(ELEMENT, NAMESPACE);
310    }
311
312    /**
313     * 
314     * Represents the fields that will be returned from a search. This information is useful when 
315     * you try to use the jabber:iq:search namespace to return dynamic form information.
316     *
317     * @author Gaston Dombiak
318     */
319    public static class ReportedData {
320        public static final String ELEMENT = "reported";
321
322        private List<FormField> fields = new ArrayList<FormField>();
323        
324        public ReportedData(List<FormField> fields) {
325            this.fields = fields;
326        }
327
328        /**
329         * Returns the fields returned from a search.
330         * 
331         * @return the fields returned from a search.
332         */
333        public List<FormField> getFields() {
334            return Collections.unmodifiableList(new ArrayList<FormField>(fields));
335        }
336
337        public CharSequence toXML() {
338            XmlStringBuilder buf = new XmlStringBuilder();
339            buf.openElement(ELEMENT);
340            // Loop through all the form items and append them to the string buffer
341            for (FormField field : getFields()) {
342                buf.append(field.toXML());
343            }
344            buf.closeElement(ELEMENT);
345            return buf;
346        }
347    }
348    
349    /**
350     * 
351     * Represents items of reported data.
352     *
353     * @author Gaston Dombiak
354     */
355    public static class Item {
356        public static final String ELEMENT = "item";
357
358        private List<FormField> fields = new ArrayList<FormField>();
359        
360        public Item(List<FormField> fields) {
361            this.fields = fields;
362        }
363        
364        /**
365         * Returns the fields that define the data that goes with the item.
366         * 
367         * @return the fields that define the data that goes with the item.
368         */
369        public List<FormField> getFields() {
370            return Collections.unmodifiableList(new ArrayList<FormField>(fields));
371        }
372        
373        public CharSequence toXML() {
374            XmlStringBuilder buf = new XmlStringBuilder();
375            buf.openElement(ELEMENT);
376            // Loop through all the form items and append them to the string buffer
377            for (FormField field : getFields()) {
378                buf.append(field.toXML());
379            }
380            buf.closeElement(ELEMENT);
381            return buf;
382        }
383    }
384}