Skip to content

The Unified and Autonomous Development Platform

midwork

robin shine9bf99fec2416
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/ImageUtils.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/ImageUtils.java
deleted file mode 100644
index 3656b6b2e0..0000000000
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/ImageUtils.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.pmease.commons.wicket;
-
-public class ImageUtils {
-
- public static boolean isWebSafe(String fileName) {
- fileName = fileName.toLowerCase();
- return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
- || fileName.endsWith(".gif") || fileName.endsWith(".png");
- }
-
-}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/WicketServletConfigurator.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/WicketServletConfigurator.java
index 5fd62ebbcd..05403fb6f1 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/WicketServletConfigurator.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/WicketServletConfigurator.java
@@ -8,6 +8,7 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import com.pmease.commons.jetty.ServletConfigurator;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentUploadServlet;
@Singleton
public class WicketServletConfigurator implements ServletConfigurator {
@@ -28,6 +29,7 @@ public class WicketServletConfigurator implements ServletConfigurator {
* match a path pattern
*/
context.addServlet(servletHolder, "/");
+ context.addServlet(AttachmentUploadServlet.class, "/attachment_upload");
}
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
index fa6c5495ab..3eda25ab75 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.css
@@ -251,4 +251,25 @@ input.clearable::-ms-clear {display: none;}
/* WEB SOCKET ERROR */
#websocket-error {display: none; position: fixed; left: 50%; top: 0; background: #f2dede;
border: 1px solid #ebccd1; color: #a94442; padding: 4px 8px; margin-left: -120px;}
-#websocket-error span {width: 16px; height: 16px; background: url("error.png") 0 0 no-repeat;}
\ No newline at end of file
+#websocket-error span {width: 16px; height: 16px; background: url("error.png") 0 0 no-repeat;}
+
+/* FILE INPUT */
+.btn-file {
+ position: relative;
+ overflow: hidden;
+}
+.btn-file input[type=file] {
+ position: absolute;
+ top: 0;
+ right: 0;
+ min-width: 100%;
+ min-height: 100%;
+ font-size: 100px;
+ text-align: right;
+ filter: alpha(opacity=0);
+ opacity: 0;
+ outline: none;
+ background: white;
+ cursor: inherit;
+ display: block;
+}
\ No newline at end of file
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentSupport.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentSupport.java
index 0cefbced12..fe2483ddae 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentSupport.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentSupport.java
@@ -1,19 +1,20 @@
package com.pmease.commons.wicket.behavior.markdown;
+import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
-import org.apache.wicket.markup.html.form.upload.FileUpload;
-
public interface AttachmentSupport extends Serializable {
- int getAttachmentMaxSize();
+ long getAttachmentMaxSize();
List<String> getAttachments();
- String getAttachmentUrl(String attachment);
+ String getAttachmentUrl(String attachmentName);
+
+ String saveAttachment(String suggestedAttachmentName, InputStream attachmentStream);
- String saveAttachment(FileUpload upload);
+ void deleteAttachemnt(String attachmentName);
- void deleteAttachemnt(String attachment);
+ long getAttachmentSize(String attachmentName);
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentUploadServlet.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentUploadServlet.java
new file mode 100644
index 0000000000..e559de99c8
--- /dev/null
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/AttachmentUploadServlet.java
@@ -0,0 +1,29 @@
+package com.pmease.commons.wicket.behavior.markdown;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.apache.wicket.util.crypt.Base64;
+
+@SuppressWarnings("serial")
+public class AttachmentUploadServlet extends HttpServlet {
+
+ protected void doPost(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ String fileName = request.getHeader("File-Name");
+ if (fileName == null) {
+ request.getHeader("Content-Type");
+ }
+ AttachmentSupport attachmentSuppport = (AttachmentSupport) SerializationUtils
+ .deserialize(Base64.decodeBase64(request.getHeader("Attachment-Support")));
+ String attachmentName = attachmentSuppport.saveAttachment(fileName, request.getInputStream());
+ response.getWriter().print(attachmentSuppport.getAttachmentUrl(attachmentName));
+ response.setStatus(HttpServletResponse.SC_OK);
+ }
+
+}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.html b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.html
index 283c773d5b..97a0cb504a 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.html
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.html
@@ -1,22 +1,24 @@
<wicket:panel>
+ <div class="modal-header">
+ <h4 class="modal-title">Insert Image</h4>
+ </div>
<div class="modal-body insert-image">
+ <div wicket:id="feedback" class="feedback"></div>
<form wicket:id="form" class="image-info">
- <div wicket:id="feedback" class="feedback"></div>
<div class="form-group">
- <label>Image URL</label>
- <input wicket:id="url" class="form-control"></input>
+ <input wicket:id="url" class="form-control focusable"></input>
</div>
- <div class="actions">
- <button wicket:id="insert" type="submit" class="btn btn-primary">Insert</button>
- <button wicket:id="cancel" class="btn btn-default" type="button">Cancel</button>
- </div>
</form>
<div wicket:id="attachments"></div>
</div>
+ <div class="modal-footer">
+ <button wicket:id="insert" type="submit" class="btn btn-primary">Insert</button>
+ <button wicket:id="cancel" class="btn btn-default" type="button">Cancel</button>
+ </div>
<wicket:fragment wicket:id="attachmentsFrag">
<div class="thumbnails">
- <div wicket:id="rows" class="row clearfix">
- <div wicket:id="columns" class="column pull-left">
+ <div wicket:id="rows" class="image-row clearfix">
+ <div wicket:id="columns" class="image-column pull-left">
<a wicket:id="link" tabindex="0">
<img wicket:id="image"></img>
</a>
@@ -25,7 +27,13 @@
<div wicket:id="noImages" class="no-images">No existing images</div>
</div>
<form wicket:id="form">
- <input wicket:id="file" type="file"></input>
+ <span class="btn btn-default btn-file">
+ Select local image (jpeg, png, gif)... <input wicket:id="file" type="file" accept=".png, .jpg, .jpeg, .gif"></input>
+ </span>
</form>
+ <div class="alert alert-info">
+ <i class="fa fa-info-circle"></i> Note: you may drag and drop to insert image directly
+ without opening this dialog, or paste image from clipboard if using Chrome.
+ </div>
</wicket:fragment>
</wicket:panel>
\ No newline at end of file
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.java
index 17499504ce..9419bae2c5 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/InsertImagePanel.java
@@ -1,10 +1,12 @@
package com.pmease.commons.wicket.behavior.markdown;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
-import javax.annotation.Nullable;
-
+import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
@@ -15,6 +17,7 @@ import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
@@ -22,17 +25,19 @@ import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.util.lang.Bytes;
+import org.apache.wicket.util.upload.FileUploadBase.SizeLimitExceededException;
+import org.apache.wicket.util.upload.FileUploadException;
import com.google.common.collect.Iterables;
-import com.pmease.commons.wicket.ImageUtils;
import com.pmease.commons.wicket.component.feedback.FeedbackPanel;
@SuppressWarnings("serial")
-public class InsertImagePanel extends Panel {
+class InsertImagePanel extends Panel {
private static final int IMAGE_COLS = 2;
- private String url = "http://";
+ private String url;
private final MarkdownBehavior markdownBehavior;
@@ -45,16 +50,9 @@ public class InsertImagePanel extends Panel {
protected void onInitialize() {
super.onInitialize();
- Form<?> form = new Form<Void>("form") {
-
- @Override
- protected void onSubmit() {
- super.onSubmit();
-
- }
-
- };
- form.add(new FeedbackPanel("feedback", form));
+ add(new FeedbackPanel("feedback", this));
+
+ Form<?> form = new Form<Void>("form");
final TextField<String> urlField = new TextField<String>("url", new IModel<String>() {
@@ -73,10 +71,12 @@ public class InsertImagePanel extends Panel {
}
});
+ urlField.setOutputMarkupId(true);
form.add(urlField);
- final AttachmentSupport attachmentSupport = getAttachmentSupport();
+ final AttachmentSupport attachmentSupport = markdownBehavior.getAttachmentSupport();
if (attachmentSupport != null) {
+ urlField.add(AttributeAppender.append("placeholder", "Input image url here or select image below"));
final Fragment fragment = new Fragment("attachments", "attachmentsFrag", this);
fragment.setOutputMarkupId(true);
@@ -87,7 +87,7 @@ public class InsertImagePanel extends Panel {
List<List<String>> rows = new ArrayList<>();
List<String> images = new ArrayList<>();
for (String attachment: attachmentSupport.getAttachments()) {
- if (ImageUtils.isWebSafe(attachment))
+ if (markdownBehavior.isWebSafeImage(attachment))
images.add(attachment);
}
for (List<String> row: Iterables.partition(images, IMAGE_COLS)) {
@@ -130,7 +130,17 @@ public class InsertImagePanel extends Panel {
});
- Form<?> fileForm = new Form<Void>("form");
+ Form<?> fileForm = new Form<Void>("form") {
+
+ @Override
+ protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
+ if (e instanceof SizeLimitExceededException)
+ error("Upload must be less than " + FileUtils.byteCountToDisplaySize(getMaxSize().bytes()));
+ }
+
+ };
+ fileForm.setMaxSize(Bytes.bytes(attachmentSupport.getAttachmentMaxSize()));
+ fileForm.setMultiPart(true);
fragment.add(fileForm);
final FileUploadField uploadField = new FileUploadField("file");
uploadField.add(new AjaxFormSubmitBehavior("change") {
@@ -138,37 +148,55 @@ public class InsertImagePanel extends Panel {
@Override
protected void onSubmit(AjaxRequestTarget target) {
super.onSubmit(target);
- if (uploadField.getFileUpload() != null) {
- attachmentSupport.saveAttachment(uploadField.getFileUpload());
- target.add(fragment);
+ FileUpload upload = uploadField.getFileUpload();
+ if (upload != null) {
+ String attachment;
+ try (InputStream is = upload.getInputStream()) {
+ attachment = attachmentSupport.saveAttachment(upload.getClientFileName(), is);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ target.add(InsertImagePanel.this);
+ String imageUrl = attachmentSupport.getAttachmentUrl(attachment);
+ String script = String.format("$('#%s').val('%s');",
+ urlField.getMarkupId(),
+ StringEscapeUtils.escapeEcmaScript(imageUrl));
+ target.appendJavaScript(script);
}
}
+
+ @Override
+ protected void onError(AjaxRequestTarget target) {
+ super.onError(target);
+ target.add(InsertImagePanel.this);
+ }
});
fileForm.add(uploadField);
add(fragment);
} else {
+ urlField.add(AttributeAppender.append("placeholder", "Input image url here"));
add(new WebMarkupContainer("attachments"));
}
- form.add(new AjaxButton("insert") {
+ add(new AjaxButton("insert", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
if (StringUtils.isBlank(url)) {
- form.error("Url should not be empty");
- target.add(form);
+ form.error("Image url should be specified");
+ target.add(InsertImagePanel.this);
} else if (!url.startsWith("http://") && !url.startsWith("https://")) {
- form.error("Url should start with http:// or https://");
- target.add(form);
+ form.error("Image url should start with http:// or https://");
+ target.add(InsertImagePanel.this);
} else {
markdownBehavior.insertImage(target, url);
}
}
});
- form.add(new AjaxLink<Void>("cancel") {
+ add(new AjaxLink<Void>("cancel") {
@Override
public void onClick(AjaxRequestTarget target) {
@@ -176,13 +204,9 @@ public class InsertImagePanel extends Panel {
}
});
- form.setOutputMarkupId(true);
add(form);
- }
-
- @Nullable
- protected AttachmentSupport getAttachmentSupport() {
- return null;
+
+ setOutputMarkupId(true);
}
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/MarkdownBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/MarkdownBehavior.java
index 2904f824ff..92f94e5fd1 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/MarkdownBehavior.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/MarkdownBehavior.java
@@ -7,6 +7,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.Component;
@@ -14,7 +17,7 @@ import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method;
-import org.apache.wicket.ajax.attributes.CallbackParameter;
+import static org.apache.wicket.ajax.attributes.CallbackParameter.*;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
@@ -25,6 +28,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.PackageResourceReference;
+import org.apache.wicket.util.crypt.Base64;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -131,7 +135,7 @@ public class MarkdownBehavior extends AbstractDefaultAjaxBehavior {
target.appendJavaScript(script);
} else if (type.equals("insertImage")) {
CommonPage page = (CommonPage) getComponent().getPage();
- imageInserter = newInsertImagePanel(page.getComponents().newChildId());
+ imageInserter = new InsertImagePanel(page.getComponents().newChildId(), this);
imageInserter.setOutputMarkupId(true);
page.getComponents().add(imageInserter);
imageInserter.setMarkupId(getComponent().getMarkupId() + "-imageinserter");
@@ -141,10 +145,6 @@ public class MarkdownBehavior extends AbstractDefaultAjaxBehavior {
}
}
- protected InsertImagePanel newInsertImagePanel(String id) {
- return new InsertImagePanel(id, this);
- }
-
public void insertImage(AjaxRequestTarget target, String url) {
CommonPage page = (CommonPage) imageInserter.getPage();
page.getComponents().remove(imageInserter);
@@ -163,6 +163,12 @@ public class MarkdownBehavior extends AbstractDefaultAjaxBehavior {
target.appendJavaScript(script);
}
+ public boolean isWebSafeImage(String fileName) {
+ fileName = fileName.toLowerCase();
+ return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
+ || fileName.endsWith(".gif") || fileName.endsWith(".png");
+ }
+
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
@@ -186,10 +192,25 @@ public class MarkdownBehavior extends AbstractDefaultAjaxBehavior {
new JavaScriptResourceReference(MarkdownBehavior.class, "markdown.js")));
response.render(CssHeaderItem.forReference(MarkdownCssResourceReference.INSTANCE));
- String script = String.format("pmease.commons.markdown.setup('%s', %s, %s);",
+ String encodedAttachmentSupport;
+ AttachmentSupport attachmentSupport = getAttachmentSupport();
+ if (attachmentSupport != null) {
+ encodedAttachmentSupport = Base64.encodeBase64String(SerializationUtils.serialize(attachmentSupport));
+ encodedAttachmentSupport = StringEscapeUtils.escapeEcmaScript(encodedAttachmentSupport);
+ encodedAttachmentSupport = "'" + encodedAttachmentSupport + "'";
+ } else {
+ encodedAttachmentSupport = "undefined";
+ }
+ String script = String.format("pmease.commons.markdown.init('%s', %s, %s, %s);",
component.getMarkupId(true), ATWHO_LIMIT,
- getCallbackFunction(CallbackParameter.explicit("type"), CallbackParameter.explicit("param")));
+ getCallbackFunction(explicit("type"), explicit("param")),
+ encodedAttachmentSupport);
response.render(OnDomReadyHeaderItem.forScript(script));
}
+ @Nullable
+ public AttachmentSupport getAttachmentSupport() {
+ return null;
+ }
+
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.css b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.css
index a3a33ea68b..049d5c84b2 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.css
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.css
@@ -81,16 +81,32 @@
color: #333;
background: rgba(0, 0, 0, 0.04);
}
+.md-preview img {
+ max-width: 100%;
+}
.insert-image .image-info {
margin-bottom: 20px;
}
.insert-image .thumbnails {
- max-height: 512px;
+ max-height: 360px;
overflow: auto;
+ margin-bottom: 20px;
}
.insert-image .thumbnails img {
- width: 256px;
- height: 256px;
+ max-width: 265px;
+ max-height: 180px;
+}
+.insert-image .image-row {
margin-bottom: 20px;
+}
+.insert-image .image-row:last-child {
+ margin-bottom: 0;
+}
+.insert-image .image-column:FIRST-CHILD {
+ margin-right: 20px;
+}
+.insert-image .alert {
+ margin-bottom: 0;
+ margin-top: 20px;
}
\ No newline at end of file
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.js
index 85b4acd693..9c16199980 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.js
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/markdown/markdown.js
@@ -1,5 +1,5 @@
pmease.commons.markdown = {
- setup: function(inputId, atWhoLimit, callback) {
+ init: function(inputId, atWhoLimit, callback, attachmentSupport) {
var $input = $("#" + inputId);
$input.markdown({
@@ -66,7 +66,8 @@ pmease.commons.markdown = {
}
}]
}]],
- iconlibrary: "fa"
+ iconlibrary: "fa",
+ resize: "vertical"
});
$input.css({resize: "vertical"});
@@ -109,6 +110,63 @@ pmease.commons.markdown = {
insertTpl: ':${name}:',
limit: atWhoLimit
});
+
+ if (attachmentSupport) {
+ var input = $input[0];
+
+ input.addEventListener("paste", function(e) {
+ for (var i = 0; i < e.clipboardData.items.length; i++) {
+ var item = e.clipboardData.items[i];
+ if (item.type.indexOf("image") != -1) {
+ var file = item.getAsFile();
+ uploadFile(file);
+ }
+ break;
+ }
+ });
+
+ input.addEventListener("dragover", function(e) {
+ e.stopPropagation();
+ e.preventDefault();
+ }, false);
+
+ input.addEventListener("dragleave", function(e) {
+ e.stopPropagation();
+ e.preventDefault();
+ }, false);
+
+ input.addEventListener("drop", function(e) {
+ e.stopPropagation();
+ e.preventDefault();
+ var files = e.target.files || e.dataTransfer.files;
+ if (files && files.length != 0)
+ uploadFile(files[0]);
+ }, false);
+
+ function uploadFile(file) {
+ var xhr = new XMLHttpRequest();
+ xhr.upload.onprogress = function(e) {
+ var percentComplete = (e.loaded / e.total) * 100;
+ console.log("Uploaded: " + percentComplete + "%");
+ };
+ xhr.onload = function() {
+ if (xhr.status == 200) {
+ alert("Sucess! Upload completed.\n\n" + xhr.responseText);
+ } else {
+ alert("Error! Upload failed");
+ }
+ };
+ xhr.onerror = function() {
+ alert("Error! Upload failed. Can not connect to server.");
+ };
+ xhr.open("POST", url, true);
+ xhr.setRequestHeader("Content-Type", file.type);
+ if (file.name)
+ xhr.setRequestHeader("File-Name", file.name);
+ xhr.setRequestHeader("Attachment-Support", attachmentSupport);
+ xhr.send(file);
+ }
+ }
},
onEmojisLoaded: function(inputId, emojis) {
var $input = $("#" + inputId);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebServletConfigurator.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebServletConfigurator.java
index 6cc9ca1ff6..d5e988660d 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebServletConfigurator.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebServletConfigurator.java
@@ -8,7 +8,6 @@ import org.eclipse.jetty.servlet.ServletHolder;
import com.pmease.commons.jetty.ClasspathAssetServlet;
import com.pmease.commons.jetty.ServletConfigurator;
import com.pmease.gitplex.web.assets.Assets;
-import com.pmease.gitplex.web.page.test.UploadServlet;
@Singleton
public class WebServletConfigurator implements ServletConfigurator {
@@ -18,8 +17,6 @@ public class WebServletConfigurator implements ServletConfigurator {
ServletHolder servletHolder = new ServletHolder(new ClasspathAssetServlet(Assets.class));
context.addServlet(servletHolder, "/assets/*");
context.addServlet(servletHolder, "/favicon.ico");
-
- context.addServlet(UploadServlet.class, "/upload");
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentAttachmentSupport.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentAttachmentSupport.java
index 9a2ac6d2b5..1cc597cc7d 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentAttachmentSupport.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentAttachmentSupport.java
@@ -10,10 +10,11 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.tika.io.IOUtils;
-import org.apache.wicket.markup.html.form.upload.FileUpload;
+import org.apache.wicket.request.Url;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
+import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.util.FileUtils;
import com.pmease.commons.util.StringUtils;
import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
@@ -23,18 +24,25 @@ import com.pmease.gitplex.core.model.PullRequest;
import com.pmease.gitplex.web.resource.AttachmentResource;
import com.pmease.gitplex.web.resource.AttachmentResourceReference;
-public abstract class CommentAttachmentSupport implements AttachmentSupport {
+public class CommentAttachmentSupport implements AttachmentSupport {
private static final long serialVersionUID = 1L;
- private static final int MAX_FILE_SIZE = 50;
+ private static final int MAX_FILE_SIZE = 50*1024*1024; // mega bytes
private static final int BUFFER_SIZE = 1024*64;
-
+
+ private final Long requestId;
+
+ public CommentAttachmentSupport(Long requestId) {
+ this.requestId = requestId;
+ }
+
@Override
public String getAttachmentUrl(String attachment) {
PageParameters params = AttachmentResource.paramsOf(getRequest(), attachment);
- return RequestCycle.get().urlFor(new AttachmentResourceReference(), params).toString();
+ String url = RequestCycle.get().urlFor(new AttachmentResourceReference(), params).toString();
+ return RequestCycle.get().getUrlRenderer().renderFullUrl(Url.parse(url));
}
@Override
@@ -49,33 +57,6 @@ public abstract class CommentAttachmentSupport implements AttachmentSupport {
return attachments;
}
- @Override
- public String saveAttachment(FileUpload upload) {
- String clientFileName = upload.getClientFileName();
- String fileName = clientFileName;
- File attachmentsDir = getAttachmentsDir();
- int index = 2;
- while (new File(attachmentsDir, fileName).exists()) {
- if (clientFileName.contains(".")) {
- String nameBeforeExt = StringUtils.substringBeforeLast(clientFileName, ".");
- String ext = StringUtils.substringAfterLast(clientFileName, ".");
- fileName = nameBeforeExt + "-" + index + "." + ext;
- } else {
- fileName = clientFileName + "-" + index;
- }
- index++;
- }
-
- File file = new File(attachmentsDir, fileName);
- try ( InputStream is = upload.getInputStream();
- OutputStream os = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
- IOUtils.copy(is, os);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return file.getName();
- }
-
private File getAttachmentsDir() {
return GitPlex.getInstance(StorageManager.class).getAttachmentsDir(getRequest());
}
@@ -88,9 +69,41 @@ public abstract class CommentAttachmentSupport implements AttachmentSupport {
}
@Override
- public int getAttachmentMaxSize() {
+ public long getAttachmentMaxSize() {
return MAX_FILE_SIZE;
}
- protected abstract PullRequest getRequest();
+ @Override
+ public long getAttachmentSize(String attachment) {
+ return new File(getAttachmentsDir(), attachment).length();
+ }
+
+ private PullRequest getRequest() {
+ return GitPlex.getInstance(Dao.class).load(PullRequest.class, requestId);
+ }
+
+ @Override
+ public String saveAttachment(String suggestedAttachmentName, InputStream attachmentStream) {
+ String attachmentName = suggestedAttachmentName;
+ File attachmentsDir = getAttachmentsDir();
+ int index = 2;
+ while (new File(attachmentsDir, attachmentName).exists()) {
+ if (suggestedAttachmentName.contains(".")) {
+ String nameBeforeExt = StringUtils.substringBeforeLast(suggestedAttachmentName, ".");
+ String ext = StringUtils.substringAfterLast(suggestedAttachmentName, ".");
+ attachmentName = nameBeforeExt + "_" + index + "." + ext;
+ } else {
+ attachmentName = suggestedAttachmentName + "_" + index;
+ }
+ index++;
+ }
+
+ File file = new File(attachmentsDir, attachmentName);
+ try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
+ IOUtils.copy(attachmentStream, os);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return file.getName();
+ }
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentInput.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentInput.java
index 49567a5639..58e3ee402b 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentInput.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CommentInput.java
@@ -26,7 +26,6 @@ import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.hibernate.dao.EntityCriteria;
import com.pmease.commons.util.StringUtils;
import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.behavior.markdown.InsertImagePanel;
import com.pmease.commons.wicket.behavior.markdown.MarkdownBehavior;
import com.pmease.gitplex.core.GitPlex;
import com.pmease.gitplex.core.model.PullRequest;
@@ -38,13 +37,10 @@ public class CommentInput extends TextArea<String> {
private final IModel<PullRequest> requestModel;
- private final IModel<String> contentModel;
-
public CommentInput(String id, IModel<PullRequest> requestModel, IModel<String> contentModel) {
- super(id);
+ super(id, contentModel);
this.requestModel = requestModel;
- this.contentModel = contentModel;
}
@Override
@@ -93,22 +89,8 @@ public class CommentInput extends TextArea<String> {
}
@Override
- protected InsertImagePanel newInsertImagePanel(String id) {
- return new InsertImagePanel(id, this) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new CommentAttachmentSupport() {
-
- @Override
- protected PullRequest getRequest() {
- return requestModel.getObject();
- }
-
- };
- }
-
- };
+ public AttachmentSupport getAttachmentSupport() {
+ return new CommentAttachmentSupport(requestModel.getObject().getId());
}
@Override
@@ -140,7 +122,6 @@ public class CommentInput extends TextArea<String> {
@Override
protected void onDetach() {
requestModel.detach();
- contentModel.detach();
super.onDetach();
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.html
index fcac683282..0e1275288b 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.html
@@ -1,9 +1,10 @@
<wicket:extend>
<div class="attachments">
<div class="upload">
- <div class="title">Select file to upload</div>
<form wicket:id="form">
- <input wicket:id="fileUpload" type="file" class="btn btn-default"></input>
+ <span class="btn btn-primary btn-file">
+ Select file to upload... <input wicket:id="file" type="file"></input>
+ </span>
<div wicket:id="feedback" class="feedback"></div>
</form>
</div>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.java
index 5e150841dc..1a507ab49e 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/RequestAttachmentsPage.java
@@ -1,32 +1,35 @@
package com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.attachments;
-import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.List;
+import java.util.Map;
import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.upload.FileUpload;
+import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.link.ResourceLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.util.lang.Bytes;
+import org.apache.wicket.util.upload.FileUploadBase.SizeLimitExceededException;
+import org.apache.wicket.util.upload.FileUploadException;
import com.pmease.commons.util.FileUtils;
import com.pmease.commons.wicket.behavior.ConfirmBehavior;
import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
import com.pmease.commons.wicket.component.feedback.FeedbackPanel;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.model.PullRequest;
import com.pmease.gitplex.core.model.Repository;
import com.pmease.gitplex.web.component.comment.CommentAttachmentSupport;
import com.pmease.gitplex.web.page.repository.pullrequest.requestdetail.RequestDetailPage;
@@ -34,74 +37,77 @@ import com.pmease.gitplex.web.page.repository.pullrequest.requestlist.RequestLis
import com.pmease.gitplex.web.resource.AttachmentResource;
import com.pmease.gitplex.web.resource.AttachmentResourceReference;
-import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.fileinput.BootstrapFileInputField;
-
@SuppressWarnings("serial")
public class RequestAttachmentsPage extends RequestDetailPage {
- private final AttachmentSupport attachmentSupport = new CommentAttachmentSupport() {
-
- @Override
- protected PullRequest getRequest() {
- return getPullRequest();
- }
-
- };
+ private final AttachmentSupport attachmentSupport;
public RequestAttachmentsPage(PageParameters params) {
super(params);
+
+ attachmentSupport = new CommentAttachmentSupport(getPullRequest().getId());
}
@Override
protected void onInitialize() {
super.onInitialize();
- final BootstrapFileInputField uploadField = new BootstrapFileInputField("fileUpload");
+ final FileUploadField uploadField = new FileUploadField("file");
- final File attachmentsDir = GitPlex.getInstance(StorageManager.class).getAttachmentsDir(getPullRequest());
-
final WebMarkupContainer available = new WebMarkupContainer("available") {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(attachmentsDir.listFiles().length != 0);
+ setVisible(!attachmentSupport.getAttachments().isEmpty());
}
};
available.setOutputMarkupPlaceholderTag(true);
add(available);
- Form<?> form = new Form<Void>("form") {
+ final Form<?> form = new Form<Void>("form") {
@Override
- protected void onSubmit() {
- super.onSubmit();
-
- if (uploadField.getFileUpload() != null) {
- attachmentSupport.saveAttachment(uploadField.getFileUpload());
- success("File has been uploaded.");
- AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
- target.add(this);
+ protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
+ if (e instanceof SizeLimitExceededException)
+ error("Upload must be less than " + FileUtils.byteCountToDisplaySize(getMaxSize().bytes()));
+ }
+
+ };
+ form.setMaxSize(Bytes.bytes(attachmentSupport.getAttachmentMaxSize()));
+ form.setMultiPart(true);
+
+ uploadField.add(new AjaxFormSubmitBehavior("change") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target) {
+ super.onSubmit(target);
+ FileUpload upload = uploadField.getFileUpload();
+ if (upload != null) {
+ try (InputStream is = upload.getInputStream()) {
+ attachmentSupport.saveAttachment(upload.getClientFileName(), is);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ form.success("File has been uploaded.");
+ target.add(form);
target.add(available);
}
}
-
+
@Override
- protected void onError() {
- super.onError();
- RequestCycle.get().find(AjaxRequestTarget.class).add(this);
+ protected void onError(AjaxRequestTarget target) {
+ super.onError(target);
+ target.add(form);
}
- };
- form.setMaxSize(Bytes.megabytes(attachmentSupport.getAttachmentMaxSize()));
- form.setMultiPart(true);
-
- form.add(new FeedbackPanel("feedback", form));
- form.add(uploadField);
+ });
+ form.add(uploadField);
+ form.add(new FeedbackPanel("feedback", form));
form.setOutputMarkupId(true);
-
add(form);
available.add(new ListView<String>("attachments", new LoadableDetachableModel<List<String>>() {
@@ -115,20 +121,20 @@ public class RequestAttachmentsPage extends RequestDetailPage {
@Override
protected void populateItem(ListItem<String> item) {
- String attachment = item.getModelObject();
- final File attachmentFile = new File(attachmentsDir, attachment);
+ final String attachment = item.getModelObject();
Link<Void> link = new ResourceLink<Void>("link", new AttachmentResourceReference(),
AttachmentResource.paramsOf(getPullRequest(), attachment));
link.add(new Label("label", attachment));
item.add(link);
- item.add(new Label("size", FileUtils.byteCountToDisplaySize(attachmentFile.length())));
+ long attachmentSize = attachmentSupport.getAttachmentSize(attachment);
+ item.add(new Label("size", FileUtils.byteCountToDisplaySize(attachmentSize)));
item.add(new AjaxLink<Void>("delete") {
@Override
public void onClick(AjaxRequestTarget target) {
- FileUtils.deleteFile(attachmentFile);
+ attachmentSupport.deleteAttachemnt(attachment);
target.add(available);
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/request-attachments.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/request-attachments.css
index a6cd292adb..44b4edaedb 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/request-attachments.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/repository/pullrequest/requestdetail/attachments/request-attachments.css
@@ -1,5 +1,4 @@
-#request-detail>.attachments>.upload>.title {
- font-size: 17px;
+#request-detail>.attachments>.upload {
margin-bottom: 8px;
}
#request-detail>.attachments>.upload>form>.feedback {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
index d2706cd561..52347806c0 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
@@ -1,8 +1,2 @@
<wicket:extend>
- <div style="width: 200px; height: 200px; background: grey"
- id="pasteTarget">Click and paste here.</div>
- <form action="upload" method="POST">
- <input type="file" id="file" name="file"/>
- <input type="text" id="text"></input>
- </form>
</wicket:extend>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
index ed9894bda7..e11cdcd792 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java
@@ -1,9 +1,6 @@
package com.pmease.gitplex.web.page.test;
import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
import com.pmease.gitplex.web.page.base.BasePage;
@@ -20,10 +17,6 @@ public class TestPage extends BasePage {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(
- new JavaScriptResourceReference(TestPage.class, "test.js")));
- response.render(OnDomReadyHeaderItem.forScript("initUpload('/upload');"));
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/UploadServlet.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/UploadServlet.java
deleted file mode 100644
index d88d61711e..0000000000
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/UploadServlet.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.pmease.gitplex.web.page.test;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class UploadServlet extends HttpServlet {
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //Compute the output file name extension based on image MIME type
- String mimeType = request.getContentType();
- String extension = null;
- String supportedFormatTable[][] = {
- {"image/png", "png"},
- {"image/jpeg", "jpg"},
- {"image/gif", "gif"}
- };
-
- for (int i = 0; i < supportedFormatTable.length; ++i) {
- if (supportedFormatTable[i][0].equals(mimeType)) {
- extension = supportedFormatTable[i][1];
-
- break;
- }
- }
-
- if (extension == null) {
- throw new IOException("Unsupported data type: " + mimeType);
- }
-
- //Read the file contents from the input stream
- File saveTo = new File("w:\\temp\\image." + extension);
- FileOutputStream os = new FileOutputStream(saveTo);
- InputStream is = request.getInputStream();
- byte buff[] = new byte[256];
- int len;
-
- while ((len = is.read(buff)) > 0) {
- os.write(buff, 0, len);
- }
- os.close();
-
- //Show the file name in browser
- PrintWriter out = response.getWriter();
-
- out.println("Saved image to: " + saveTo.getAbsolutePath());
- }
-}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/test.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/test.js
deleted file mode 100644
index f4d71143d2..0000000000
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-initUpload = function(url) {
- var pasteTarget = document.getElementById("pasteTarget");
- pasteTarget.addEventListener("paste", handlePaste);
-
- $("#file").change(function() {
- console.log("hello");
- uploadFile(this.files[0]);
- });
-
- pasteTarget.addEventListener("dragover", function(e) {
- e.stopPropagation();
- e.preventDefault();
- }, false);
-
- pasteTarget.addEventListener("dragleave", function(e) {
- e.stopPropagation();
- e.preventDefault();
- }, false);
-
- pasteTarget.addEventListener("drop", function(e) {
- e.stopPropagation();
- e.preventDefault();
- var files = e.target.files || e.dataTransfer.files;
- uploadFile(files[0]);
- }, false);
-
- function handlePaste(e) {
- for (var i = 0; i < e.clipboardData.items.length; i++) {
- var item = e.clipboardData.items[i];
- console.log("Item type: " + item.type);
- if (item.type.indexOf("image") != -1) {
- uploadFile(item.getAsFile());
- } else {
- alert("Discarding non-image paste data");
- }
- }
- }
- function uploadFile(file) {
- var xhr = new XMLHttpRequest();
- xhr.upload.onprogress = function(e) {
- var percentComplete = (e.loaded / e.total) * 100;
- console.log("Uploaded: " + percentComplete + "%");
- };
- xhr.onload = function() {
- if (xhr.status == 200) {
- alert("Sucess! Upload completed.\n\n" + xhr.responseText);
- } else {
- alert("Error! Upload failed");
- }
- };
- xhr.onerror = function() {
- alert("Error! Upload failed. Can not connect to server.");
- };
- console.log("post to: " + url);
- xhr.open("POST", url, true);
- xhr.setRequestHeader("Content-Type", file.type);
- xhr.send(file);
- }
-}