How to get the file extension in grails? - 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

Related

Jenkins pipeline: join file / URL paths

How can I join strings nicely into a path when programming Jenkins Groovy pipeline? So that I can join('http://example.com/', '/r', 'some.html') -> 'http://example.com/r/some.html'
This note suggests using new File(dir1, dir2) or Paths.get(dir1, dir2) in "pure" Groovy.
However in Jenkins pipeline, import java.nio.file.Paths gives me
No such static method found: staticMethod java.nio.file.Paths get java.lang.String org.codehaus.groovy.runtime.GStringImpl.
and with new File I get
Scripts not permitted to use new java.io.File java.lang.String java.lang.String. Administrators can decide whether to approve or reject this signature.
and I kinda agree with Jenkins on this do not want to allow this. Is there another way?
bad idea to build url with Paths or File objects because under windows you'll get wrong result.
you can build url with simple string concatenation and use URI.normalize() to remove extra slashes:
def u = new URI(['http://example.com/', '/r', 'some.html'].join('/')).normalize().toString()
Try this:
def join_two_urls(url1, url2) {
if (url1 == "" || url2 == "") {
println "Error: must provde two invalid urls."
return ""
}
println "Joining ${url1} and ${url2} ..."
if (url1 ==~ /.*\/$/) {
url1 = url1.substring(0, url1.length() - 1)
}
if (url2 ==~ /^\/.*/) {
url2 = url2.substring(1, url2.length())
}
return url1 + "/" + url2
}
def join_paths(String[] urls) {
if (urls.size() <= 1) {
println "Error: invalid urls."
return ""
}
conbined_url = ""
pre_url = ""
for (url in urls) {
if (pre_url == "") {
pre_url = url
continue
}
conbined_url += join_two_urls(pre_url, url)
}
return conbined_url
}
println join_paths("xx/", "xxx/" , "/fsdsdfsdf")

Groovy Script - Logback configuration unawaited behaviour

I want to use Logback as my logging framework within Grails. therefore I set up everything in place to work but my implementation fails on the configuration file itself. the reason is, as I guess, somewhere whithin the scoping of Groovy Script but I'm not able to figure it out...
if I define my String properties without any identifier which I want to use later I get a warning that it may not be accessed. For example:
LOG_DIR = 'c:/temp/myproject/logs/'
BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
I get the following error message from Logback, which I'm pretty sure is indicating that both LOG_DIR and BACKUP_DIR can not be reached:
13:33:32,036 |-ERROR in ch.qos.logback.classic.gaffer.AppenderDelegate#6fd00b - Appender [F_MAIN] of type [ch.qos.logback.core.rolling.RollingFileAppender] has no appplicable [LOG_DIR] property
13:33:32,068 |-ERROR in ch.qos.logback.classic.gaffer.ComponentDelegate#788ac3 - Component of type [ch.qos.logback.core.rolling.FixedWindowRollingPolicy] has no appplicable [BACKUP_DIR] property
I also tried the following approach by declaring both variables with the #Field tag, but it still does not work:
#Field String LOG_DIR = 'c:/temp/myproject/logs/'
#Field String BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
what am I doing wrong here?
oh my!
after searching and a lot of trial/error I found the solution and it was so close and definitely seems obvious now: I had to declare both variables with def, so now they are visible throughout the whole script ;)
For example, this is working code:
def LOG_DIR = 'c:/temp/myproject/logs/'
def BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
now, I'm also able to use a function like this within my script:
def createFilename(String directory, String name, boolean isBackupFile) {
String filename = ''
if(isBackupFile) {
filename = "${directory}backup/MyProject-${name}.%d{yyyy-MM-dd}.%i.log.zip"
} else {
filename = "${directory}MyProject-${name}.log"
}
return filename
}
def fileAppenderLog = createFilename(LOG_DIR, 'output', false)
def fileAppenderLogBackup = createFilename(LOG_DIR, 'output', true)
appender('F_MAIN', RollingFileAppender) {
file = fileAppenderLog
rollingPoliciy(FixedWindowRollingPolicy) {
fileNamePattern = fileAppenderLogBackup
// .... and so on
}
}
which is pretty useful, I think :), especially if you want to declare a bunch of different logfiles and even if you want to declare temporary logfiles which are created when Logback is rescanning this file ...

Parsing Multi-part in 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"
}

commonsMultipartFile trouble

Hi I have am trying to implement a file upload in my application where the file uploaded is parsed and an entry is created in the database using that information.
def save = {
def file = request.getFile("file");
def filename = file.getOriginalFilename();
def type = filename.split('\\.');
if(!file.isEmpty()){
if(type[1] == "properties"){
redirect(action:"parsePropertyFile", params:params);
}
}
}
def parsePropertyFile = {
println "\n"
println params.file;
println "\n";
def f = params.file;
println f;
def filename = f.getOriginalFilename();
println filename;
}
when I print out f this is output:
org.springframework.web.multipart.commons.CommonsMultipartFile#29d32df9
but when I try to call getOriginalFilename() on f I get the following error:
groovy.lang.MissingMethodException: No signature of method:
java.lang.String.getOriginalFilename() is applicable for argument types: () values: []
I also printed out file from the save function and the output of that is also:
org.springframework.web.multipart.commons.CommonsMultipartFile#29d32df9
so why am I getting the error?
Instead of redirecting, can you just call your another function? Redirect will issue an http redirect with the file as param with no need.
if(type[1] == "properties") {
parsePropertyFile(file)
}
And then:
private def parsePropertyFile(def file) {
String filename = file.getOriginalFilename();
...
}
In your parsePropertyFile action you aren't getting a File object, you're getting the String from params. Just like in your save action, you need to do
def f = request.getFile('file')
println f.getOriginalFilename()

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]}"))

Resources