summaryrefslogtreecommitdiffstats
path: root/idrop-web/grails-app/controllers/org/irods/mydrop/controller/FileController.groovy
blob: cd7710621bb2ab2c85bf6cd349b88b009631a608 (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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package org.irods.mydrop.controller


import grails.converters.*

import org.irods.jargon.core.connection.IRODSAccount
import org.irods.jargon.core.exception.DataNotFoundException
import org.irods.jargon.core.exception.JargonException
import org.irods.jargon.core.exception.JargonRuntimeException
import org.irods.jargon.core.pub.CollectionAndDataObjectListAndSearchAO
import org.irods.jargon.core.pub.DataTransferOperations
import org.irods.jargon.core.pub.IRODSAccessObjectFactory
import org.irods.jargon.core.pub.Stream2StreamAO
import org.irods.jargon.core.pub.domain.DataObject
import org.irods.jargon.core.pub.io.IRODSFile
import org.irods.jargon.core.pub.io.IRODSFileFactory
import org.irods.jargon.core.pub.io.IRODSFileInputStream
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.multipart.MultipartFile


class FileController {

	IRODSAccessObjectFactory irodsAccessObjectFactory
	IRODSAccount irodsAccount
	static long MAX_UPLOAD = 3221225472  // shooting for 3GB max, make parm?

	/**
	 * Interceptor grabs IRODSAccount from the SecurityContextHolder
	 */
	def beforeInterceptor = {
		def irodsAuthentication = SecurityContextHolder.getContext().authentication

		if (irodsAuthentication == null) {
			throw new JargonRuntimeException("no irodsAuthentication in security context!")
		}

		irodsAccount = irodsAuthentication.irodsAccount
		log.debug("retrieved account for request: ${irodsAccount}")
	}

	def afterInterceptor = {
		log.debug("closing the session")
		irodsAccessObjectFactory.closeSession()
	}


	/**
	 * This is the download action
	 */
	def index = {

		log.info("index action")
		String parseString = "/file/download"
		def parseStringLength = parseString.length()
		String fullPath = params.name
		if (fullPath == null || fullPath.isEmpty()) {
			log.error("null or missing path info")
			throw new JargonException("null or missing path info")
		}

		log.info("add path info is ${params.name}")
		def idx = fullPath.indexOf(parseString)
		log.debug("parsing out additional path info")
		if (idx == -1) {
			log.error("unable to parse addl path info for irods absolute path, path info was ${fullPath}")
			throw new JargonException("unable to parse addl path info for irods absolute path")
		}

		fullPath = fullPath.substring(idx + parseStringLength)
		log.info("iRODS path for file is: ${fullPath}")


		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFileInputStream irodsFileInputStream = irodsFileFactory.instanceIRODSFileInputStream(fullPath)
		IRODSFile irodsFile = irodsFileFactory.instanceIRODSFile(fullPath)
		def length =  irodsFile.length()
		log.info("file length = ${length}")
		log.info("opened input stream")

		response.setContentType("application/octet-stream")
		response.setContentLength((int) length)
		response.setHeader("Content-disposition", "attachment;filename=\"${irodsFile.name}\"")

		response.outputStream << irodsFileInputStream // Performing a binary stream copy

	}

	/**
	 * Prepare a dialog to upload a file into the given collection
	 * 
	 */
	def prepareUploadDialog = {
		log.info("prepareUploadDialog")
		String irodsTargetCollection = params.irodsTargetCollection
		if (irodsTargetCollection == null || irodsTargetCollection.isEmpty()) {
			log.error("null or missing irodsTargetCollection")
		}

		log.info("looking up parent as: ${irodsTargetCollection}")

		/* here we could do any processing on irods, such as provisioning of metadata fields based on target
		 * for now, derive info about the target and normalize to a collection (could be a data object)
		 */

		CollectionAndDataObjectListAndSearchAO collectionAndDataObjectListAndSearchAO = irodsAccessObjectFactory.getCollectionAndDataObjectListAndSearchAO(irodsAccount)

		def targetObject = null
		try {
			targetObject = collectionAndDataObjectListAndSearchAO.getFullObjectForType(irodsTargetCollection)
		} catch (DataNotFoundException dnf) {
			log.error("no iRODS data found for: ${irodsTargetCollection}")
			throw new JargonException("No data found for ${irodsTargetCollection}")
		}

		if (targetObject instanceof DataObject) {
			log.info("substituting data object parent as path")
			DataObject dataObject = (DataObject) targetObject
			irodsTargetCollection = dataObject.collectionName
		}

		render(view:"uploadDialog", model:[irodsTargetCollection:irodsTargetCollection])
	}

	/**
	 * Process an actual call to upload data to iRODS as a multi-part file
	 */
	def upload = {
		log.info("upload action in file controller")
		MultipartFile f = request.getFile('file')
		def name = f.getOriginalFilename()

		log.info("f is ${f}")
		log.info("length of f is ${f.size}")
		log.info("max upload size is ${MAX_UPLOAD}")

		if (f.size > MAX_UPLOAD) {
			log.error("file size is too large, send error message to use bulk upload")
			def message = message(code:"error.use.bulk.upload")
			response.sendError(500,message)
			return
		} else if (f.size == 0) {
			log.error("file is zero length")
			def message = message(code:"error.zero.length.upload")
			response.sendError(500,message)
			return
		}

		log.info("name is : ${name}")
		def irodsCollectionPath = params.collectionParentName

		if (f == null || f.empty) {
			log.error("no file to upload")
			throw new JargonException("No file to upload")
		}

		if (irodsCollectionPath == null || irodsCollectionPath.empty) {
			log.error("no target iRODS collection given in upload request")
			throw new JargonException("No iRODS target collection given for upload")
		}

		InputStream fis = null
		log.info("building irodsFile for file name: ${name}")


		try {
			fis = new BufferedInputStream(f.getInputStream())
			IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
			IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(irodsCollectionPath, name)
			targetFile.setResource(irodsAccount.defaultStorageResource)
			Stream2StreamAO stream2Stream = irodsAccessObjectFactory.getStream2StreamAO(irodsAccount)
			stream2Stream.transferStreamToFileUsingIOStreams(fis, targetFile, f.size, 0)
		} catch (Exception e) {
			log.error("exception in upload transfer", e)
			response.sendError(500,e.message)
		} finally {
			// stream2Stream will close input and output streams
		}

		render "{\"name\":\"${name}\",\"type\":\"image/jpeg\",\"size\":\"1000\"}"
	}

	/**
	 * Delete the given file or folder
	 */
	def deleteFileOrFolder = {
		log.info("delete file or folder")
		String absPath = params['absPath']
		if (!absPath) {
			log.error "no absPath in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		absPath = absPath.trim()

		log.info("name for delete folder:${absPath}")
		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(absPath)

		targetFile.deleteWithForceOption()
		log.info("file deleted")
		render targetFile.getParent()
	}

	/**
	 * Process a bulk delete action based on data input from the browse details form
	 */
	def deleteBulkAction = {
		log.info("deleteBulkAction")

		log.info("params: ${params}")

		def filesToDelete = params['selectDetail']

		// if nothing selected, just jump out and return a message
		if (!filesToDelete) {
			log.info("no files to delete")
			render "OK"
			return
		}

		log.info("filesToDelete: ${filesToDelete}")

		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)

		if (filesToDelete instanceof Object[]) {
			log.debug "is array"
			filesToDelete.each{
				log.info "filesToDelete: ${it}"
				IRODSFile toDelete = irodsFileFactory.instanceIRODSFile(it)
				toDelete.delete()
			}

		} else {
			log.debug "not array"
			log.info "deleting: ${filesToDelete}"
			IRODSFile toDelete = irodsFileFactory.instanceIRODSFile(filesToDelete)
			toDelete.delete()
		}

		render "OK"
	}


	/**
	 * Add a new iRODS folder
	 */
	def createFolder = {
		log.info("create folder")

		String parent = params['parent']
		if (!parent) {
			log.error "no parent in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		parent = parent.trim()

		String newFolderName = params['name']
		if (!newFolderName) {
			log.error "no name in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		newFolderName = newFolderName.trim()

		log.info("name for create folder:${newFolderName}")
		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFile targetFile = irodsFileFactory.instanceIRODSFile(parent + "/" + newFolderName)

		if (targetFile.exists()) {
			log.error "no name in request"
			def message = message(code:"error.duplicate.file")
			response.sendError(500,message)
		}

		targetFile.mkdirs()
		log.info("file created:${targetFile.absolutePath}")
		render targetFile.getAbsolutePath()
	}

	/**
	 * Rename an iRODS file or folder
	 */
	def renameFile = {
		log.info("renameFile()")

		String prevAbsPath = params['prevAbsPath']
		if (!prevAbsPath) {
			log.error "no prevAbsPath in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		prevAbsPath = prevAbsPath.trim()

		String newName = params['newName']
		if (!newName) {
			log.error "no newName in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		newName = newName.trim()

		log.info("rename to :${newName}")
		IRODSFileFactory irodsFileFactory = irodsAccessObjectFactory.getIRODSFileFactory(irodsAccount)
		IRODSFile prevFile = irodsFileFactory.instanceIRODSFile(prevAbsPath)

		IRODSFile newFile = irodsFileFactory.instanceIRODSFile(prevFile.getParentFile(), newName)

		// don't rename to self
		if (newFile.absolutePath == prevFile.absolutePath) {
			log.info("ignoring rename to self")
			render prevFile.absolutePath
			return
		}

		prevFile.renameTo(newFile)

		// return the parent, which will be reloaded
		render newFile.parent
	}

	/**
	 * Move a file in iRODS
	 */
	def moveFile = {
		log.info("move file")
		String sourceAbsPath = params['sourceAbsPath']
		String targetAbsPath = params['targetAbsPath']

		if (!sourceAbsPath) {
			log.error "no source path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		if (!targetAbsPath) {
			log.error "no target path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		DataTransferOperations dataTransferOperations = irodsAccessObjectFactory.getDataTransferOperations(irodsAccount)
		log.info("moving ${sourceAbsPath} to ${targetAbsPath}")
		dataTransferOperations.move(sourceAbsPath, targetAbsPath)
		render targetAbsPath
	}

	/** 
	 * Copy a file in iRODS
	 */
	def copyFile = {
		log.info("copy file")
		String sourceAbsPath = params['sourceAbsPath']
		String targetAbsPath = params['targetAbsPath']

		if (!sourceAbsPath) {
			log.error "no source path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		if (!targetAbsPath) {
			log.error "no target path in request"
			def message = message(code:"error.no.path.provided")
			response.sendError(500,message)
		}

		DataTransferOperations dataTransferOperations = irodsAccessObjectFactory.getDataTransferOperations(irodsAccount)
		log.info("copy ${sourceAbsPath} to ${targetAbsPath}")
		dataTransferOperations.copy(sourceAbsPath,"", targetAbsPath,null, false, null) //TODO: resource here?
		render targetAbsPath

	}
}