aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/com/vaadin/ui/dnd/FileDropTarget.java
blob: 59197cbc26ba26369b132e28d0d4ed3240e49e65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
 * Copyright 2000-2016 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.vaadin.ui.dnd;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.vaadin.server.ServletPortletHelper;
import com.vaadin.server.StreamVariable;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.ui.dnd.FileDropTargetClientRpc;
import com.vaadin.shared.ui.dnd.FileDropTargetRpc;
import com.vaadin.shared.ui.dnd.FileDropTargetState;
import com.vaadin.shared.ui.dnd.FileParameters;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.ConnectorTracker;
import com.vaadin.ui.Html5File;
import com.vaadin.ui.UI;
import com.vaadin.ui.dnd.event.FileDropEvent;

/**
 * Extension to add drop target functionality to a widget for accepting and
 * uploading files.
 * <p>
 * Dropped files are handled in the {@link FileDropHandler} given in the
 * constructor. The file details are first sent to the handler, which can then
 * decide which files to upload to server by setting a {@link StreamVariable}
 * with {@link Html5File#setStreamVariable(StreamVariable)}.
 *
 * @param <T>
 *            Type of the component to be extended.
 * @author Vaadin Ltd
 * @since 8.1
 */
public class FileDropTarget<T extends AbstractComponent>
        extends DropTargetExtension<T> {

    /**
     * Handles the file drop event.
     */
    private final FileDropHandler<T> fileDropHandler;

    /**
     * Extends {@code target} component and makes it a file drop target. A file
     * drop handler needs to be added to handle the file drop event.
     *
     * @param target
     *            Component to be extended.
     * @param fileDropHandler
     *            File drop handler that handles the file drop event.
     * @see FileDropEvent
     */
    public FileDropTarget(T target, FileDropHandler<T> fileDropHandler) {
        super(target);

        this.fileDropHandler = fileDropHandler;

        registerRpc(new FileDropTargetRpc() {
            @Override
            public void drop(Map<String, FileParameters> fileParams) {
                onDrop(fileParams);
            }

            @Override
            public void poll() {
                // Polling server for changes after upload finished
            }
        });
    }

    /**
     * Invoked when a file or files have been dropped on client side. Fires the
     * {@link FileDropEvent}.
     *
     * @param fileParams
     *            map from file ids to actual file details
     */
    protected void onDrop(Map<String, FileParameters> fileParams) {
        Map<String, Html5File> files = new HashMap<>();
        Map<String, String> urls = new HashMap<>();

        // Create a collection of html5 files
        fileParams.forEach((id, fileParameters) -> {
            Html5File html5File = new Html5File(fileParameters.getName(),
                    fileParameters.getSize(), fileParameters.getMime());
            files.put(id, html5File);
        });

        // Call drop handler with the collection of dropped files
        FileDropEvent<T> event = new FileDropEvent<>(getParent(),
                files.values());
        fileDropHandler.drop(event);

        // Create upload URLs for the files that the drop handler
        // attached stream variable to
        files.entrySet().stream()
                .filter(entry -> entry.getValue().getStreamVariable() != null)
                .forEach(entry -> {
                    String id = entry.getKey();
                    Html5File file = entry.getValue();

                    String url = createUrl(file, id);
                    urls.put(id, url);
                });

        // Send upload URLs to the client if there are files to be
        // uploaded
        if (urls.size() > 0) {
            getRpcProxy(FileDropTargetClientRpc.class).sendUploadUrl(urls);
        }
    }

    /**
     * Creates an upload URL for the given file and file ID.
     *
     * @param file
     *            File to be uploaded.
     * @param id
     *            Generated ID for the file.
     * @return Upload URL for uploading the file to the server.
     */
    private String createUrl(Html5File file, String id) {
        return getStreamVariableTargetUrl("rec-" + id,
                new FileReceiver(id, file));
    }

    private String getStreamVariableTargetUrl(String name,
            StreamVariable value) {
        String connectorId = getConnectorId();
        UI ui = getUI();
        int uiId = ui.getUIId();
        String key = uiId + "/" + connectorId + "/" + name;

        ConnectorTracker connectorTracker = ui.getConnectorTracker();
        connectorTracker.addStreamVariable(connectorId, name, value);
        String secKey = connectorTracker.getSeckey(value);

        return ApplicationConstants.APP_PROTOCOL_PREFIX
                + ServletPortletHelper.UPLOAD_URL_PREFIX + key + "/" + secKey;
    }

    @Override
    protected FileDropTargetState getState() {
        return (FileDropTargetState) super.getState();
    }

    @Override
    protected FileDropTargetState getState(boolean markAsDirty) {
        return (FileDropTargetState) super.getState(markAsDirty);
    }

    /**
     * Returns the component this extension is attached to.
     *
     * @return Extended component.
     */
    @Override
    @SuppressWarnings("unchecked")
    public T getParent() {
        return super.getParent();
    }

    private class FileReceiver implements StreamVariable {

        private final String id;
        private Html5File file;

        public FileReceiver(String id, Html5File file) {
            this.id = id;
            this.file = file;
        }

        private boolean listenProgressOfUploadedFile;

        @Override
        public OutputStream getOutputStream() {
            if (file.getStreamVariable() == null) {
                return null;
            }
            return file.getStreamVariable().getOutputStream();
        }

        @Override
        public boolean listenProgress() {
            return file.getStreamVariable().listenProgress();
        }

        @Override
        public void onProgress(StreamingProgressEvent event) {
            file.getStreamVariable()
                    .onProgress(new ReceivingEventWrapper(event));
        }

        @Override
        public void streamingStarted(StreamingStartEvent event) {
            listenProgressOfUploadedFile = file.getStreamVariable() != null;
            if (listenProgressOfUploadedFile) {
                file.getStreamVariable()
                        .streamingStarted(new ReceivingEventWrapper(event));
            }
        }

        @Override
        public void streamingFinished(StreamingEndEvent event) {
            if (listenProgressOfUploadedFile) {
                file.getStreamVariable()
                        .streamingFinished(new ReceivingEventWrapper(event));
            }
        }

        @Override
        public void streamingFailed(final StreamingErrorEvent event) {
            if (listenProgressOfUploadedFile) {
                file.getStreamVariable()
                        .streamingFailed(new ReceivingEventWrapper(event));
            }
        }

        @Override
        public boolean isInterrupted() {
            return file.getStreamVariable().isInterrupted();
        }

        /*
         * With XHR2 file posts we can't provide as much information from the
         * terminal as with multipart request. This helper class wraps the
         * terminal event and provides the lacking information from the
         * FileParameters.
         */
        class ReceivingEventWrapper implements StreamingErrorEvent,
                StreamingEndEvent, StreamingStartEvent, StreamingProgressEvent {

            private final StreamingEvent wrappedEvent;

            ReceivingEventWrapper(StreamingEvent e) {
                wrappedEvent = e;
            }

            @Override
            public String getMimeType() {
                return file.getType();
            }

            @Override
            public String getFileName() {
                return file.getFileName();
            }

            @Override
            public long getContentLength() {
                return file.getFileSize();
            }

            @Override
            public Exception getException() {
                if (wrappedEvent instanceof StreamingErrorEvent) {
                    return ((StreamingErrorEvent) wrappedEvent).getException();
                }
                return null;
            }

            @Override
            public long getBytesReceived() {
                return wrappedEvent.getBytesReceived();
            }

            /**
             * Calling this method has no effect. DD files are receive only once
             * anyway.
             */
            @Override
            public void disposeStreamVariable() {

            }
        }

    }
}