Replace the string in file using groovy - grails

I have got a file with name "silent.txt". This file is having a line as follows
bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName
I want to replace the above text with
bop4InstallDir = "/abc/xyz/pqr"
Using groovy script how do I accomplish this?
Please help.

Not very elegant, but this should work.
def file = new File("silent.txt")
file.text = file.text.replace('bop4InstallDir = myProps.cordys_install_dir + "/" + instanceName',
'bop4InstallDir = "/abc/xyz/pqr"')

Is silent.txt well formatted property file? In this case you can use a various ways to access them, much more secure, than dumb replace.
Look groovy: How to access to properties file?
or ConfigSlurper

The following code worked:
def file = new File("silent.txt")
def fileText = file.replaceAll("bop4InstallDir\\ \\=\\ myProps.cordys_install_dir\\ \\+\\ \"\\/\"\\ \\+\\ instanceName", "bop4InstallDir\\ \\=\\ \"/opt/cordys/bop4/defaultInst1\"")
file.write(fileText);

Related

How Can I Use Config Entries with Dots When Parsing with XmlSlurper

I'm trying to use a groovy Config entry to parse an xml file with XmlSlurper.
Here's the Config file:
sample {
xml {
frompath = "Email.From"
}
}
Here's the XML
<xml>
<Email>
<From>
<Address>foo#bar.com</Address>
<Alias>Foo Bar</Alias>
</From>
<Email>
</xml>
This is what I tried initially:
XmlSlurper slurper = new XmlSlurper()
def record = slurper.parseText((new File("myfile.xml")).text)
def emailFrom = record?."${grailsApplication.config.sample.xml.frompath}".Address.text()
This doesn't work because XmlSlurper allows one to use special characters in path names as long as they're surrounded by quotes, so the app is translating this as:
def emailFrom = record?."Email.From".Address.text()
and not
def emailFrom = record?.Email.From.Address.text()
I tried setting the frompath property to be "Email"."From" and then '"Email"."From"'. I tried tokenizing the property in the middle of the parse statement (don't ask.)
Can someone please point me towards some resources to find out if/how I can do this?
I feel like this issue getting dynamic Config parameter in Grails taglib and this https://softnoise.wordpress.com/2013/07/29/grails-injecting-config-parameters/ may have whispers of a solution, but I need fresh eyes to see it.
The solution in issue getting dynamic Config parameter in Grails taglib is a proper way to deref down such a path. E.g.
def emailFrom = 'Email.From'.tokenize('.').inject(record){ r,it -> r."$it" }
def emailFromAddress = emailFrom.Address.text()
If your path there can get complex and you rather go with the potentially more dangerous way, you could also use Eval. E.g.
def path = "a[0].b.c"
def map = [a:[[b:[c:666]]]] // dummy map, same as xmlslurper
assert Eval.x(map, "x.$path") == 666

How to add file extension inside of url with ruby

This url:
url = rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id
I would like to add the extension mp3 to all file name.
In this case the file name is cancion
The id of lesson is a dynamic value.
I would like to get this url something like:
url = rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion.mp3?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id
Thanks!
You can parse the URI, edit the path, then return the value
require 'uri/http'
u = URI.parse('rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id')
u.path += ".mp3"
puts u.to_s
or use a simple regexp replace
u = 'rtmp://xxxxxxxxxxxxxx.cloudfront.net/cfx/st/mp3:audios/lesson/2/cancion?Expires=1386332537&Signature=mysignature__&Key-Pair-Id=my-key-par-id'
u.gsub('?', '.mp3?')
The second approach can be used only if you can assume the format of the input is always the same.
You can do simple gsub since this is URL and you can expect one occurrence of ? so simple do.
url.gsub!('?', '.mp3?')
Usually I would go regex here but no need from previously stated reason.

How to get rid of the starting slash in URI or URL?

I am using
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
String path2 = path.substring(1);
because the output of the method getPath() returns sth like this:
/C:/Users/......
and I need this
C:/Users....
I really need the below address because some external library refuses to work with the slash at the beginning or with file:/ at the beginning or anything else.
I tried pretty much all the methods in URL like toString() toExternalPath() etc. and done the same with URI and none of it returns it like I need it. (I totally don't understand, why it keeps the slash at the beginning).
It is okay to do it on my machine with just erasing the first char. But a friend tried to run it on linux and since the addresses are different there, it does not work...
What should with such problem?
Convert the URL to a URI and use that in the File constructor:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
File file = new File(res.toURI());
String fileName = file.getPath();
As long as UNIX paths are not supposed to contain drive letters, you may try this:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
char a_char = text.charAt(2);
if (a_char==':') path = path.substring(1);
Convert to a URI, then use Paths.get().
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();
You could probably just format the string once you get it.
something like this:
path2= path2[1:];
I was searching for one-line solution, so the best what i came up with was deleting it manually like this:
String url = this.getClass().getClassLoader().getResource(dictionaryPath).getPath().replaceFirst("/","");
In case if someone also needs to have it on different OS, you can make IF statement with
System.getProperty("os.name");

URL manipulation: http://example.com/foo.jpg -> http://example.com/foo.preview.png

In rails I want to wrote some code to change this url string
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg
to
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.png
Should I use regular Expression to change it?
I'm new to Regexp, anyone can show me how to do this, and how to learn this stuff
thanks
If the extension is of fixed length, you're better off using string slicing.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
print url[0..-5] + ".preview" + url[-4..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpg
Or if your extensions are of variable length you can use rindex() to find the start of the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
dot_index = url.rindex(".")-1
print url[0..dot_index] + ".preview" + url[dot_index+1..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you must use a regex then do it like this:
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
print url.gsub(/\.(\w{2,4})$/, ".preview.\\1")
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you're sure the file ends with .jpg, you can to
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
url.gsub(".jpg", ".preview.jpg")
Otherwise, you can get the filename, then append the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
ext = File.extname(url)
url.gsub(ext, ".preview{ext}")
A string replace seems to be enough.
".jpg" -> ".preview.png"
Unfortunately I do not know ruby.
In python it'll be
new_url = url.replace(".jpg",".preview.png",1)
I think that it'll be similar in ruby. It seems to be sub() instead.
new_url = url.sub(".jpg",".preview.png")

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