Parsing Multi-part in Grails - grails

I want to design a controller in Grails which accepts multipart like "XML+binary file1+binary file2+...". How could I parse this request? I appreciate any sample codes!
Thanks,
Reza

So I'm assuming you are talking about an input type file that has the multiple attribute. Here is how you would process it server side:
List<MultipartFile> files = request.multiFileMap.nameOfInputFileElement
files.each { uploadedFile ->
if(!uploadedFile.empty){
File newFile = new File( parentDir, uploadedFile.originalFilename)
uploadedFile.transferTo(newFile)
}
}

I would do something like:
def uploadedFile = request.getFile('filepath')
if (uploadedFile && !uploadedFile.empty)
println "file:${uploadedFile?.originalFilename} uploaded"
}

Related

Unable to split the list of files

I am having list of files in a directory.
For Ex:
sample1.properties
sample2.properties
sample3.properties
I am trying to use the groovy code to push these values in the Jenkins Active Choices parameter. How can I populate this list without ".properties" at the end. My list of Active choices parameters needs to be like this:
sample1
sample2
sample3
Code I am using is:
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
data= results.tree.path
data.each {
it -> if(it.endsWith(".properties"))
choices.push(it.replace("/","") )
}
choices=choices.sort()
choices.add(0,"SELECT")
return choices
Simply replacing the .properties part will not work?
choices.push(it.replace("/","").replace(".properties", ""))
If my assumption regarding your results.tree.path content is correct, then you should probably use something like that:
def data = [
'some/complex/path/sample1.properties',
'some/complex/path/some_irrelevant_file.txt',
'some/complex/path/sample2.properties',
'some/complex/path/sample3.properties'
]
data.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { println it }
so, in your case, you need to do:
results.tree.path.findAll { it.endsWith('.properties') }
.collect { it.split('/').last().replace('.properties', '') }
.each { choices.push(it) }

RestBuilder Plugin. How can I upload a file without creating a file?

Currently, I can upload files(exist) with Grails's RestBuilder.
However, I want to upload a file without creating a file .
I want to create binary data (= Text File) in a program and send it directly
Is it possible?
RestBuilder rest = new RestBuilder()
RestResponse resp = rest.post(url){
contentType("multipart/form-data")
setProperty("dataFile",[filePath])// <- it can
setProperty("dataFile",[ byte[] or inputStream() or String ? ])// <- Is it possible?
}
'''
I'm sure you figured this out already, but you can just use a String reference or a byte[] just as you can use File instances for the multipart request using RestBuilder. It should 'just work' e.g.
RestBuilder rest = new RestBuilder()
RestResponse response = rest.post(url) {
contentType 'multipart/form-data'
stringPart = 'hello' // String
bytePart = '68656c6c6f'.decode64() // byte[]
filePart = new File('/path/to/file.jpg') // File
}

How to get the file extension in grails?

I recently started working on grails and i want to know how to get the
extension of a file. Ex: test.txt. I want to check extension(txt)?
any clue?
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~ to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)
Hope i found the answer of my Question. How to find the extension
of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}
Lsat comment at this post

Image upload to filesystem in Grails

I'm implementing a file upload functionality to a web-app in Grails. This includes adapting existing code to allow multiple file extensions. In the code, I've implemented a boolean to verify that the file path exists, but I'm still getting a FileNotFoundException that /hubbub/images/testcommand/photo.gif (No such file or directory)
My upload code is
def rawUpload = {
def mpf = request.getFile("photo")
if (!mpf?.empty && mpf.size < 200*1024){
def type = mpf.contentType
String[] splitType = type.split("/")
boolean exists= new File("/hubbub/images/${params.userId}")
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
} else {
tempFile = new File("/hubbub/images/${params.userId}").mkdir()
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
}
}
I'm getting the exception message at
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
So, why is this error happening, as I'm simply collatating an valid existing path as well as a valid filename and extension?
Why do you think that convertation of File object to Boolean returns existence of a file?
Try
File dir = new File("/hubbub/images/${params.userId}")
if (!dir.exists()) {
assert dir.mkdirs()
}
mpf.transferTo(new File(dir, "picture.${splitType[1]}"))

How to export pdf report in jasper reports

I want to export a report as pdf and it should ask the user for a download location. How do I do this in grails?
This is my code:
def exportToPdf(JasperPrint jasperPrint,String path,request){
String cur_time =System.currentTimeMillis();
JRExporter pdfExporter = null;
pdfExporter = new JRPdfExporter();
log.debug("exporting to file..."+JasperExportManager.exportReportToPdfFile(jasperPrint, "C:\\pdfReport"+cur_time+".pdf"));
return ;
}
In jasper controller:
/**
* Generate a html response.
*/
def generateResponse = {reportDef ->
if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) {
response.setHeader("Content-disposition", "attachment; filename=\"" + reportDef.name + "." + reportDef.fileFormat.extension + "\"");
response.contentType = reportDef.fileFormat.mimeTyp
response.characterEncoding = "UTF-8"
response.outputStream << reportDef.contentStream.toByteArray()
} else {
render(text: reportDef.contentStream, contentType: reportDef.fileFormat.mimeTyp, encoding: reportDef.parameters.encoding ? reportDef.parameters.encoding : 'UTF-8');
}
}
Have you looked at the Jasper Plugin? It seems to have the tools already built for you. As far as asking the user for a download location the browser has some controller over how files are received from a web page. Is your real issue that you want control over the download location?
[UPDATE]
Using the location 'c:\' is on your server not the client and this is why it is not downloading.
try something like this...
def controllerMethod = {
def temp_file = File.createTempFile("jasperReport",".pdf") //<-- you don't have to use a temp file but don't forget to delete them off the server at some point.
JasperExportManager.exportReportToPdfFile(jasperPrint, temp_file.absolutePath));
response.setContentType("application/pdf") //<-- you'll have to handle this dynamically at some point
response.setHeader("Content-disposition", "attachment;filename=${temp_file.getName()}")
response.outputStream << temp_file.newInputStream() //<-- binary stream copy to client
}
I have not tested this and there are better ways of handling the files and streams but i think you'll get the general idea.

Resources