Getting list of files - grails

I have a directory named 'import' and would like to get all files and their corresponding date (based on filename). Sample content of the directory is this:
input_02202010.xls
input_02212010.xls
input_02222010.xls
I would like to have a Map that contains the path of the file and a Date variable.
Can anyone show me how Groovy will solve this?

Use new File("/foo/bar/import").list() to get the file names, just like you would in Java. Then create file objects from the strings and check lastModified() for the last modification date.
EDIT:
Groovy adds eachFile() methods to java.io.File, we can use that to make it a bit more groovy...
To extract the date from the filename, use
Date d = new java.text.SimpleDateFormat("MMddyyyy").parse(filename.substring(6,14))
To make it all into a map (using the filename as key and the date as value, though redundant):
def df = new java.text.SimpleDateFormat("MMddyyyy")
def results = [:]
new File("/foo/bar/import").eachFile() { file ->
results.put(file.getName(), df.parse(file.getName().substring(6,14)))
}
results

Related

Replacing strings using str_replace_all with excel file

I'm trying to replace a very long list of strings (200+) with the str_replace all function. I would like to be able to read in an excel file which has the R code for the replacements as the list of replacements to so that I don't have 200+ lines in my script dedicated to naming strings, but can't seem to get it to work.
What I have:
`REPLACEMENTS = c(
'\\bAFFL\\b'='AFFILIATE',
'\\bACCY\\b'='ACCOUNTANCY',
'\\bACTG\\b'='ACCOUNTING',
'\\bACQUIS\\b'='ACQUISITION',
'\\bADMNR\\b'='ADMINISTRATOR',
)
df$tobereplaced = str_replace_all(df$tobereplaced, REPLACEMENTS)`
What I want:
`REPLACEMENTS = excelfile$replacements
df$tobereplaced = str_replace_all(df$tobereplaced, REPLACEMENTS)`
When I try this I get the error:
Error in fix_replacement(replacement) :
argument "replacement" is missing, with no default

How to create a DXL attribute using a #included file

I have a file containing attribute dxl. I have created a template that creates a module exactly the way I want it, with new attributes and views and such. One of the attributes needs to be a dxl attribute,but I cannot find a good way to create a new dxl attribute from a dxl script using code contained in a separate file. I thought I might try something like this:
String s = #include "filepath"
But that obviously doesn't work. Is there a way to get the contents of a separate file into a string?
Thanks
You can do this using a Stream.
Stream inFile = read "filepath"
String s, sContent = ""
while(true) {
inFile >> s
sContent = sContent "\n" s
if(end of inFile) break
}
close inFile
This will fill the string sContent with your DXL file contents. Then you can use it to create the attribute.
Updated Code based on feedback.

Create and download word file from template in MVC

I have kept a word document (.docx) in one of the project folders which I want to use as a template.
This template contains custom header and footer lines for user. I want to facilitate user to download his own data in word format. For this, I want to write a function which will accept user data and referring the template it will create a new word file replacing the place-holders in the template and then return the new file for download (without saving it to server). That means the template needs to be intact as template.
Following is what I am trying. I was able to replace the placeholder. However, I am not aware of how to give the created content as downloadable file to user. I do not want to save the new content again in the server as another word file.
public void GenerateWord(string userData)
{
string templateDoc = HttpContext.Current.Server.MapPath("~/App_Data/Template.docx");
// Open the new Package
Package pkg = Package.Open(templateDoc, FileMode.Open, FileAccess.ReadWrite);
// Specify the URI of the part to be read
Uri uri = new Uri("/word/document.xml", UriKind.Relative);
PackagePart part = pkg.GetPart(uri);
XmlDocument xmlMainXMLDoc = new XmlDocument();
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
xmlMainXMLDoc.InnerXml = ReplacePlaceHoldersInTemplate(userData, xmlMainXMLDoc.InnerXml);
// Open the stream to write document
StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
xmlMainXMLDoc.Save(partWrt);
partWrt.Flush();
partWrt.Close();
pkg.Close();
}
private string ReplacePlaceHoldersInTemplate(string toReplace, string templateBody)
{
templateBody = templateBody.Replace("#myPlaceHolder#", toReplace);
return templateBody;
}
I believe that the below line is saving the contents in the template file itself, which I don't want.
xmlMainXMLDoc.Save(partWrt);
How should I modify this code which can return the new content as downloadable word file to user?
I found the solution Here!
This code allows me to read the template file and modify it as I want and then to send response as downloadable attachment.

Grails: Replacing symbols with HTML equivalent

I'm reading a CSV file and one of the columns has text that contains symbols that is not recognized. After I read the file, symbols such as ' becomes � . I'm also saving this into a DB.
Obviously when I display this on a webpage, it shows garbage. How can I substitute HTML code (ex. &#180 ;) for this with Grails?
I am reading the CSV using the csv plugin. Code below:
def f = "clientDocs/testfile.csv"
def fReader = new File(f).toCsvMapReader([batchSize:50, charset:'UTF-8'])
fReader.each { batchList ->
batchList.each {
def description = substituteSymbols(it.Description)
def substituteSymbols(inText) {
// HOW TO SUBSTITUTE HERE
}
Thanks for any help or suggestions. I've already tried string.replaceAll(regExp).
Grails comes with a basic set of encoders/decoders for common tasks.
What you want here is it.Description.encodeAsHTML().
And then if you want the original when displaying in the view, just reverse it with .decodeHTML()
You can read more about these here: http://grails.org/doc/latest/guide/single.html#codecs
(Edited decode method name typo as per the comment)

How do I get "happy" names using Amazon S3 plugin for Grails (via Jets3t)

References:
http://www.grails.org/plugin/amazon-s3
http://svn.codehaus.org/grails-plugins/grails-amazon-s3/trunk/grails-app/services/org/grails/s3/S3AssetService.groovy
http://svn.codehaus.org/grails-plugins/grails-amazon-s3/trunk/grails-app/domain/org/grails/s3/S3Asset.groovy
By "happy" names, I mean the real name of the file I'm uploading... for instance, if I'm putting a file called "foo.png" I'd expect the url to the file to be /foo.png. Currently, I'm just getting what appears to be a GUID (with no file extension) for the file name.
Any ideas?
You can set the key field on the S3Asset object to achieve what you need.
I'll update the doco page with more information on this.
With length, inputstream and fileName given from the uploaded file, you should achieve what you want with the following code :
S3Service s3Service = new RestS3Service(new AWSCredentials(accessKey, secretKey))
S3Object up = new S3Object(s3Service.getBucket("myBucketName"), fileName)
up.setAcl AccessControlList.REST_CANNED_PUBLIC_READ
up.setContentLength length
up.setContentType "image/jpeg"
up.setDataInputStream inputstream
up = s3Service.putObject(bucket, up)
I hope it helps.
Actual solution (as provided by #leebutts):
import java.io.*;
import org.grails.s3.*;
def s3AssetService;
def file = new File("foo.png"); //assuming this file exists
def asset = new S3Asset(file);
asset.mimeType = extension;
asset.key = "foo.png"
s3AssetService.put(asset);

Resources