1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.client.ui.commons.markup.html.form;
20
21 import java.time.Duration;
22 import org.apache.commons.lang3.StringUtils;
23 import org.apache.syncope.client.ui.commons.HttpResourceStream;
24 import org.apache.syncope.client.ui.commons.MIMETypesLoader;
25 import org.apache.wicket.ajax.AjaxRequestTarget;
26 import org.apache.wicket.behavior.AbstractAjaxBehavior;
27 import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler;
28 import org.apache.wicket.request.resource.ContentDisposition;
29 import org.apache.wicket.spring.injection.annot.SpringBean;
30
31 public abstract class BinaryFieldDownload extends AbstractAjaxBehavior {
32
33 private static final long serialVersionUID = 7203445884857810583L;
34
35 @SpringBean
36 private MIMETypesLoader mimeTypesLoader;
37
38 private final String name;
39
40 private String fileKey;
41
42 private String mimeType;
43
44 private final boolean addAntiCache;
45
46 public BinaryFieldDownload(final String name, final boolean addAntiCache) {
47 super();
48 this.name = name;
49 this.addAntiCache = addAntiCache;
50 }
51
52 public BinaryFieldDownload(
53 final String name, final String fileKey, final String mimeType, final boolean addAntiCache) {
54
55 this(name, addAntiCache);
56 this.fileKey = fileKey;
57 this.mimeType = mimeType;
58 }
59
60 public void initiate(final AjaxRequestTarget target) {
61 String url = getCallbackUrl().toString();
62 if (addAntiCache) {
63 url += (url.contains("?") ? "&" : "?");
64 url = url + "antiCache=" + System.currentTimeMillis();
65 }
66 target.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
67 }
68
69 @Override
70 public void onRequest() {
71 HttpResourceStream stream = getResourceStream();
72 ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(stream);
73 String key = StringUtils.isNotBlank(fileKey) ? fileKey + '_' : "";
74 String ext = "";
75 if (StringUtils.isNotBlank(mimeType)) {
76 String extByMimeType = mimeTypesLoader.getFileExt(mimeType);
77 ext = StringUtils.isBlank(extByMimeType) ? ".bin" : ('.' + extByMimeType);
78 }
79 String fileName = key + (stream.getFilename() == null ? name : stream.getFilename()) + ext;
80
81 handler.setFileName(fileName);
82 handler.setContentDisposition(ContentDisposition.ATTACHMENT);
83 handler.setCacheDuration(Duration.ZERO);
84 getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
85 }
86
87 protected abstract HttpResourceStream getResourceStream();
88 }