View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript.host.xml;
16  
17  import java.util.ArrayList;
18  import java.util.Collections;
19  import java.util.IdentityHashMap;
20  import java.util.Iterator;
21  import java.util.List;
22  import java.util.Map;
23  
24  import org.htmlunit.FormEncodingType;
25  import org.htmlunit.WebRequest;
26  import org.htmlunit.corejs.javascript.ClassDescriptor;
27  import org.htmlunit.corejs.javascript.Context;
28  import org.htmlunit.corejs.javascript.ES6Iterator;
29  import org.htmlunit.corejs.javascript.Function;
30  import org.htmlunit.corejs.javascript.Scriptable;
31  import org.htmlunit.corejs.javascript.TopLevel;
32  import org.htmlunit.corejs.javascript.VarScope;
33  import org.htmlunit.javascript.HtmlUnitScriptable;
34  import org.htmlunit.javascript.JavaScriptEngine;
35  import org.htmlunit.javascript.configuration.JsxClass;
36  import org.htmlunit.javascript.configuration.JsxConstructor;
37  import org.htmlunit.javascript.configuration.JsxFunction;
38  import org.htmlunit.javascript.configuration.JsxSymbol;
39  import org.htmlunit.javascript.host.file.Blob;
40  import org.htmlunit.javascript.host.file.File;
41  import org.htmlunit.javascript.host.html.HTMLFormElement;
42  import org.htmlunit.util.KeyDataPair;
43  import org.htmlunit.util.MimeType;
44  import org.htmlunit.util.NameValuePair;
45  import org.htmlunit.util.StringUtils;
46  
47  /**
48   * JavaScript host object for {@code FormData}.
49   *
50   * @author Ahmed Ashour
51   * @author Ronald Brill
52   * @author Thorsten Wendelmuth
53   *
54   * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData">MDN Documentation</a>
55   */
56  @JsxClass
57  public class FormData extends HtmlUnitScriptable {
58  
59      /** Constant used to register the prototype in the context. */
60      private static final String FORM_DATA_ITERATOR_TAG = "FormData Iterator";
61  
62      private final List<NameValuePair> requestParameters_ = new ArrayList<>();
63      // the File objects of the file entries; created on demand for entries without one (e.g. from a form)
64      private final Map<NameValuePair, File> files_ = new IdentityHashMap<>();
65  
66      /**
67       * Iterator support for {@code FormData}.
68       */
69      public static final class FormDataIterator extends ES6Iterator {
70          private static final ClassDescriptor DESCRIPTOR =
71                  ES6Iterator.makeDescriptor(FORM_DATA_ITERATOR_TAG, FORM_DATA_ITERATOR_TAG);
72  
73          enum Type { KEYS, VALUES, BOTH }
74  
75          private final Type type_;
76          private final String className_;
77          private final List<NameValuePair> nameValuePairList_;
78          private final FormData formData_;
79          private int index_;
80  
81          /**
82           * Initializes the iterator prototype.
83           *
84           * @param cx the {@link Context}
85           * @param scope the scope
86           * @param className the class name
87           */
88          public static void init(final Context cx, final TopLevel scope, final String className) {
89              ES6Iterator.initialize(
90                      DESCRIPTOR, cx, scope, new FormDataIterator(className), false, FORM_DATA_ITERATOR_TAG);
91          }
92  
93          /**
94           * Creates an instance with an empty list (used for prototype initialization).
95           *
96           * @param className the class name
97           */
98          public FormDataIterator(final String className) {
99              super();
100 
101             type_ = Type.BOTH;
102             index_ = 0;
103             nameValuePairList_ = Collections.emptyList();
104             formData_ = null;
105             className_ = className;
106         }
107 
108         /**
109          * Creates an instance for iterating over the given list of name-value pairs.
110          *
111          * @param scope the scope
112          * @param className the class name
113          * @param type the iteration type (keys, values, or both)
114          * @param formData the form data to iterate
115          */
116         public FormDataIterator(final VarScope scope, final String className, final Type type,
117                 final FormData formData) {
118             super(scope, className);
119             type_ = type;
120             index_ = 0;
121             nameValuePairList_ = formData.requestParameters_;
122             formData_ = formData;
123             className_ = className;
124         }
125 
126         /**
127          * {@inheritDoc}
128          */
129         @Override
130         public String getClassName() {
131             return className_;
132         }
133 
134         /**
135          * {@inheritDoc}
136          */
137         @Override
138         protected boolean isDone(final Context cx, final VarScope scope) {
139             return index_ >= nameValuePairList_.size();
140         }
141 
142         /**
143          * {@inheritDoc}
144          */
145         @Override
146         protected Object nextValue(final Context cx, final VarScope scope) {
147             if (isDone(cx, scope)) {
148                 return Context.getUndefinedValue();
149             }
150 
151             final NameValuePair nextNameValuePair = nameValuePairList_.get(index_++);
152             return switch (type_) {
153                 case KEYS -> nextNameValuePair.getName();
154                 case VALUES -> formData_.getEntryValue(nextNameValuePair);
155                 case BOTH -> cx.newArray(scope,
156                         new Object[]{nextNameValuePair.getName(), formData_.getEntryValue(nextNameValuePair)});
157             };
158         }
159     }
160 
161     /**
162      * Creates an instance of this object, optionally pre-populated from the given form.
163      *
164      * @param formObj an {@link HTMLFormElement} to initialize the data from, or {@code undefined}
165      */
166     @JsxConstructor
167     public void jsConstructor(final Object formObj) {
168         if (formObj instanceof HTMLFormElement form) {
169             requestParameters_.addAll(form.getHtmlForm().getParameterListForSubmit(null));
170         }
171     }
172 
173     /**
174      * Appends a new value for an existing key, or adds the key if it does not already exist.
175      *
176      * @param name the name of the field
177      * @param value the field's value
178      * @param filename the filename reported to the server (optional)
179      */
180     @JsxFunction
181     public void append(final String name, final Object value, final Object filename) {
182         requestParameters_.add(createEntry(name, value, filename));
183     }
184 
185     /**
186      * Removes the entry with the given name, if it exists.
187      *
188      * @param name the name of the field to remove
189      */
190     @JsxFunction(functionName = "delete")
191     public void delete_js(final String name) {
192         if (StringUtils.isEmptyOrNull(name)) {
193             return;
194         }
195 
196         requestParameters_.removeIf(pair -> {
197             if (name.equals(pair.getName())) {
198                 files_.remove(pair);
199                 return true;
200             }
201             return false;
202         });
203     }
204 
205     /**
206      * Returns the first value associated with the given name.
207      *
208      * @param name the name of the field to retrieve
209      * @return the first value found (a string or a {@link File}), or {@code null} if not found
210      */
211     @JsxFunction
212     public Object get(final String name) {
213         if (StringUtils.isEmptyOrNull(name)) {
214             return null;
215         }
216 
217         for (final NameValuePair pair : requestParameters_) {
218             if (name.equals(pair.getName())) {
219                 return getEntryValue(pair);
220             }
221         }
222         return null;
223     }
224 
225     /**
226      * Returns all values associated with the given name.
227      *
228      * @param name the name of the field to retrieve
229      * @return an array of all values found for the given name
230      */
231     @JsxFunction
232     public Scriptable getAll(final String name) {
233         if (StringUtils.isEmptyOrNull(name)) {
234             return JavaScriptEngine.newArray(getParentScope(), 0);
235         }
236 
237         final List<Object> values = new ArrayList<>();
238         for (final NameValuePair pair : requestParameters_) {
239             if (name.equals(pair.getName())) {
240                 values.add(getEntryValue(pair));
241             }
242         }
243 
244         return JavaScriptEngine.newArray(getParentScope(), values.toArray(new Object[0]));
245     }
246 
247     /**
248      * Returns whether an entry with the given name exists.
249      *
250      * @param name the name of the field to check
251      * @return {@code true} if the name exists, {@code false} otherwise
252      */
253     @JsxFunction
254     public boolean has(final String name) {
255         if (StringUtils.isEmptyOrNull(name)) {
256             return false;
257         }
258 
259         for (final NameValuePair pair : requestParameters_) {
260             if (name.equals(pair.getName())) {
261                 return true;
262             }
263         }
264         return false;
265     }
266 
267     /**
268      * Sets a new value for an existing key, replacing all existing values for that key,
269      * or adds the key if it does not already exist.
270      *
271      * @param name the name of the field
272      * @param value the field's value
273      * @param filename the filename reported to the server (optional)
274      */
275     @JsxFunction
276     public void set(final String name, final Object value, final Object filename) {
277         if (StringUtils.isEmptyOrNull(name)) {
278             return;
279         }
280 
281         int pos = -1;
282 
283         final Iterator<NameValuePair> iter = requestParameters_.iterator();
284         int idx = 0;
285         while (iter.hasNext()) {
286             final NameValuePair pair = iter.next();
287             if (name.equals(pair.getName())) {
288                 iter.remove();
289                 files_.remove(pair);
290                 if (pos < 0) {
291                     pos = idx;
292                 }
293             }
294             idx++;
295         }
296 
297         if (pos < 0) {
298             pos = requestParameters_.size();
299         }
300 
301         requestParameters_.add(pos, createEntry(name, value, filename));
302     }
303 
304     /**
305      * Returns an iterator over all name/value pairs contained in this {@code FormData}.
306      *
307      * @return an iterator of {@code [name, value]} arrays
308      */
309     @JsxFunction
310     @JsxSymbol(symbolName = "iterator")
311     public Scriptable entries() {
312         return new FormDataIterator(getParentScope(),
313                 FORM_DATA_ITERATOR_TAG, FormDataIterator.Type.BOTH, this);
314     }
315 
316     /**
317      * Creates the entry for the given value; like the browsers, a {@link Blob} is converted to
318      * a {@link File} (named 'blob' or the given filename).
319      *
320      * @param name the name
321      * @param value the value
322      * @param filename the filename (optional)
323      * @return the new entry
324      * @see <a href="https://xhr.spec.whatwg.org/#create-an-entry">XMLHttpRequest Standard - create an entry</a>
325      */
326     private NameValuePair createEntry(final String name, final Object value, final Object filename) {
327         if (!(value instanceof Blob blob)) {
328             return new NameValuePair(name, JavaScriptEngine.toString(value));
329         }
330 
331         final boolean hasFilename = filename != null && !JavaScriptEngine.isUndefined(filename);
332         final File file;
333         if (value instanceof File valueFile && !hasFilename) {
334             file = valueFile;
335         }
336         else {
337             final String fileName = hasFilename ? JavaScriptEngine.toString(filename) : "blob";
338             final long lastModified = value instanceof File original
339                     ? original.getLastModified() : System.currentTimeMillis();
340             file = new File(blob.getBytes(), fileName, blob.getType(), lastModified);
341             file.setParentScope(getParentScope());
342             file.setPrototype(getPrototype(File.class));
343         }
344 
345         final KeyDataPair entry = file.getKeyDataPair(name, file.getName());
346         files_.put(entry, file);
347         return entry;
348     }
349 
350     /**
351      * Returns the value of the given entry: a string or a {@link File}.
352      *
353      * @param entry the entry
354      * @return the value
355      */
356     Object getEntryValue(final NameValuePair entry) {
357         if (!(entry instanceof KeyDataPair keyDataPair)) {
358             return entry.getValue();
359         }
360 
361         File file = files_.get(entry);
362         if (file == null) {
363             // entries from a form
364             if (keyDataPair.getFile() != null && keyDataPair.getData() == null) {
365                 file = new File(keyDataPair.getFile());
366             }
367             else {
368                 final byte[] data = keyDataPair.getData() == null ? new byte[0] : keyDataPair.getData();
369                 final String fileName = keyDataPair.getFileName() == null ? "" : keyDataPair.getFileName();
370                 final String type = StringUtils.isEmptyOrNull(keyDataPair.getMimeType())
371                         ? MimeType.APPLICATION_OCTET_STREAM : keyDataPair.getMimeType();
372                 file = new File(data, fileName, type, System.currentTimeMillis());
373             }
374             file.setParentScope(getParentScope());
375             file.setPrototype(getPrototype(File.class));
376             files_.put(entry, file);
377         }
378         return file;
379     }
380 
381     /**
382      * Returns the entries of this {@code FormData} (strings are {@link NameValuePair}s, files and
383      * blobs are {@link org.htmlunit.util.KeyDataPair}s).
384      *
385      * @return the entries
386      */
387     public List<NameValuePair> getEntries() {
388         return Collections.unmodifiableList(requestParameters_);
389     }
390 
391     /**
392      * Populates the given {@link WebRequest} with the parameters from this {@code FormData}.
393      *
394      * @param webRequest the web request to fill
395      */
396     public void fillRequest(final WebRequest webRequest) {
397         webRequest.setEncodingType(FormEncodingType.MULTIPART);
398         webRequest.setRequestParameters(requestParameters_);
399     }
400 
401     /**
402      * Iterates over all key/value pairs in this {@code FormData}, calling the given callback for each.
403      *
404      * @param callback the function to execute for each key/value pair
405      */
406     @JsxFunction
407     public void forEach(final Object callback) {
408         if (!(callback instanceof Function fun)) {
409             throw JavaScriptEngine.typeError(
410                     "Foreach callback '" + JavaScriptEngine.toString(callback) + "' is not a function");
411         }
412 
413         // This must be indexes instead of iterator() for correct behavior when of list changes while iterating
414         for (int i = 0;; i++) {
415             if (i >= requestParameters_.size()) {
416                 break;
417             }
418 
419             final NameValuePair param = requestParameters_.get(i);
420             fun.call(Context.getCurrentContext(), getParentScope(), this,
421                         new Object[] {getEntryValue(param), param.getName(), this});
422         }
423     }
424 
425     /**
426      * Returns an iterator over all keys in this {@code FormData}.
427      *
428      * @return an iterator of key strings
429      */
430     @JsxFunction
431     public FormDataIterator keys() {
432         return new FormDataIterator(getParentScope(),
433                 FORM_DATA_ITERATOR_TAG, FormDataIterator.Type.KEYS, this);
434     }
435 
436     /**
437      * Returns an iterator over all values in this {@code FormData}.
438      *
439      * @return an iterator of the values (strings or {@link File}s)
440      */
441     @JsxFunction
442     public FormDataIterator values() {
443         return new FormDataIterator(getParentScope(),
444                 FORM_DATA_ITERATOR_TAG, FormDataIterator.Type.VALUES, this);
445     }
446 }