-
Notifications
You must be signed in to change notification settings - Fork 0
/
attach.groovy
69 lines (62 loc) · 2.5 KB
/
attach.groovy
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
import java.security.MessageDigest;
import javax.jcr.Value;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload
if (request.method != 'POST') {
request.getRequestDispatcher("view.html").forward(request, response)
}
if (ServletFileUpload.isMultipartContent(request)) {
// Create a new file upload handler
ServletFileUpload upload = [new DiskFileItemFactory()]
def node
def items = upload.getItemIterator(request)
while (items.hasNext()) {
def item = items.next()
if (item.formField && item.fieldName == 'p') {
node = context.getAttribute('jcr').getNode(item.openStream().text)
}
else {
def digest = MessageDigest.getInstance('md5')
def binary = node.session.valueFactory.createBinary(item.openStream())
// item.openStream().with {
binary.stream.with {
byte[] data = new byte[8192]
int bytesRead
while ((bytesRead = read(data)) >= 0) {
digest.update data, 0, bytesRead
}
}
def checksum = new String(Hex.encodeHex(digest.digest()))
def attachNode = node.session.rootNode << 'mn:attachments'
checksum.split(/(?<=\G.{2})/).each {
attachNode = attachNode << it
}
if (attachNode.isNew()) {
// println "Creating node: $attachNode.path"
attachNode.addMixin('mix:referenceable')
attachNode.session.save {
// attachNode['jcr:content'] = attachNode.session.valueFactory.createBinary(item.openStream())
attachNode['jcr:content'] = binary
}
}
if (node) {
node.session.save {
def attachments = node << 'mn:attachments'
attachments[item.name] = attachNode
}
// attachments = node.attachments.values as List
// }
// else {
// attachments = []
// }
// attachments << node.session.valueFactory.createValue(attachNode)
//
// node.session.save {
// node['attachments'] = attachments as Value[]
// }
}
}
}
response.sendRedirect("view.html?p=$node.path")
}