Save changes to Property File in Grails - spring

I have a grails application that reads from a property file. I created an administration page, that allows the user to view the settings in this file. I want to allow the user to update the various properties and save them back to the property file using Grails.
My problem is I cant seem to figure out how to save the changes back to the property file.
Here is my code that reads from the file and makes changes to the properties:
def env = params.getAt("environment");
if (env != null){
//Read from Property file based on user selection
def props = new Properties()
def cl = Thread.currentThread().contextClassLoader
def filepath = env+'.properties'
props.load servletContext.getResourceAsStream("/WEB-INF/"+ filepath)
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
def input = params.getAt(key)
if (input != null){
props.setProperty(key,input)
}
}
//props.store(propFile.newWriter(), null)
}
Any Ideas on how to save/overwrite the example.properties file in /WEB-INF/example.properties?

I think that you might be looking for the getRealPath method in ServletContext
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Simple example that shows you how to use it
http://82.157.70.109/mirrorbooks/javaservletjspcookbook/0596005725_jsvltjspckbk-chp-14-sect-7.html

Related

How to list all children in Google Drive's appfolder and read file contents with Xamarin / c#?

I'm trying to work with text files in the apps folder.
Here's my GoogleApiClient constructor:
googleApiClient = new GoogleApiClient.Builder(this)
.AddApi(DriveClass.API)
.AddScope(DriveClass.ScopeFile)
.AddScope(DriveClass.ScopeAppfolder)
.UseDefaultAccount()
.AddConnectionCallbacks(this)
.EnableAutoManage(this, this)
.Build();
I'm connecting with:
googleApiClient.Connect()
And after:
OnConnected()
I need to list all files inside the app folder. Here's what I got so far:
IDriveFolder appFolder = DriveClass.DriveApi.GetAppFolder(googleApiClient);
IDriveApiMetadataBufferResult result = await appFolder.ListChildrenAsync(googleApiClient);
Which is giving me the files metadata.
But after that, I don't know how to read them, edit them or save new files. They are text files created with my app's previous version (native).
I'm following the google docs for drive but the Xamarin API is a lot different and has no docs or examples. Here's the API I'm using: https://components.xamarin.com/view/googleplayservices-drive
Edit:
Here is an example to read file contents from the guide:
DriveFile file = ...
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(contentsOpenedCallback);
First I can't find anywhere in the guide what "DriveFile file = ..." means. How do I get this instance? DriveFile seems to be a static class in this API.
I tried:
IDriveFile file = DriveClass.DriveApi.GetFile(googleApiClient, metadata.DriveId);
This has two problems, first it complains that GetFile is deprecated but doesn't say how to do it properly. Second, the file doesn't have an "open" method.
Any help is appreciated.
The Xamarin binding library wraps the Java Drive library (https://developers.google.com/drive/), so all the guides/examples for the Android-based Drive API work if you keep in mind the Binding's Java to C# transformations:
get/set methods -> properties
fields -> properties
listeners -> events
static nested class -> nested class
inner class -> nested class with an instance constructor
So you can list the AppFolder's directory and files by recursively using the Metadata when the drive item is a folder.
Get Directory/File Tree Example:
await Task.Run(() =>
{
async void GetFolderMetaData(IDriveFolder folder, int depth)
{
var folderMetaData = await folder.ListChildrenAsync(_googleApiClient);
foreach (var driveItem in folderMetaData.MetadataBuffer)
{
Log.Debug(TAG, $"{(driveItem.IsFolder ? "(D)" : "(F)")}:{"".PadLeft(depth, '.')}{driveItem.Title}");
if (driveItem.IsFolder)
GetFolderMetaData(driveItem.DriveId.AsDriveFolder(), depth + 1);
}
}
GetFolderMetaData(DriveClass.DriveApi.GetAppFolder(_googleApiClient), 0);
});
Output:
[SushiHangover.FlightAvionics] (D):AppDataFolder
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData1.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData2.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData3.json
[SushiHangover.FlightAvionics] (F):AppConfiguration.json
Write a (Text) File Example:
using (var contentResults = await DriveClass.DriveApi.NewDriveContentsAsync(_googleApiClient))
using (var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream))
using (var changeSet = new MetadataChangeSet.Builder()
.SetTitle("AppConfiguration.txt")
.SetMimeType("text/plain")
.Build())
{
writer.Write("StackOverflow Rocks\n");
writer.Write("StackOverflow Rocks\n");
writer.Close();
await DriveClass.DriveApi.GetAppFolder(_googleApiClient).CreateFileAsync(_googleApiClient, changeSet, contentResults.DriveContents);
}
Note: Substitute a IDriveFolder for DriveClass.DriveApi.GetAppFolder to save a file in a subfolder of the AppFolder.
Read a (text) File Example:
Note: driveItem in the following example is an existing text/plain-based MetaData object that is found by recursing through the Drive contents (see Get Directory/File list above) or via creating a query (Query.Builder) and executing it via DriveClass.DriveApi.QueryAsync.
var fileContexts = new StringBuilder();
using (var results = await driveItem.DriveId.AsDriveFile().OpenAsync(_googleApiClient, DriveFile.ModeReadOnly, null))
using (var inputStream = results.DriveContents.InputStream)
using (var streamReader = new StreamReader(inputStream))
{
while (streamReader.Peek() >= 0)
fileContexts.Append(await streamReader.ReadLineAsync());
}
Log.Debug(TAG, fileContexts.ToString());

How to Grab an image file from Parse

So i've tried looking over the documentation and cant make heads or tails of it... so i'm hoping someone here can help:
so i've created a ParseFile with an image stored in a byte[]. I've saved this parsefile and then assigned it into a parseObject. I have then saved the parseObject
profilePicFile = new ParseFile( "profilePic.png", bytes);
Task saveProfilePic = profilePicFile.SaveAsync();
yield return saveProfilePic;
user["Profile_Pic"] = profilePicFile;
Task updateUser = user.SaveAsync();
Then i've made a temporary button just to check that this works. I've assigned it a new script. Basically when I hit the button, I just want it to grab the user, and its profile_pic and tell me if there is something there.
ParseObject receivedUser = new ParseObject("ReceivedUser");
ParseQuery<ParseObject> query = ParseObject.GetQuery("User");
query.GetAsync("DwRfTQ66tA").ContinueWith(t =>
{
receivedUser = t.Result;
});
if (receivedUser.IsDataAvailable == true) {
print ("getting data");
byte[] data = receivedUser.Get<byte[]> ("Profile_Pic");
} else {
print ("no user");
}
}
Am I doing this right? Do i need to re-initialise anything? Do I need to add the other script component to this or use Getcomponent to get the user data? (I dont think so since the ParseUser object is supposed to be a static right?). Or does this script need to re-log in to grab data from Parse?
currently the error i'm getting is KeyNotFoundException.
I deff have a User Class on parse and a Profile_Pic column. I'm using the object ID as the reference. Is this correct?
Instead of
ParseObject.GetQuery("User")
you should be using:
ParseUser.Query

Grails Generating a zip file for the user to download

I am a newbie to grails currently working on a web-app project that works with users uploading pictures. Users can create a "hunt" with a list of prompts. Each "prompt" is the objective for participants (eg: upload pictures of your favorite candy.) Basically the web-app is a "scavenger hunt" tool for Photographers to socially share their work.
Right now, I am having trouble trying write a function in my user controller to generate a zip file with all of the pictures that the user has uploaded. This is what my controller function looks like at the moment.
I used this example I found to start.
Generating a zip file.
def downloadAlbum(){
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ZipOutputStream zipFile = new ZipOutputStream(baos)
//Instance of a user domain class
def userInstance = User.findByLogin(auth.user())
//pictures are uploaded to a prompt and stored as a photoInstance
//this line of code gets the actual file stored as byte[]
photoInstance.myFile = image.getBytes()
//select all photos that belong to the user and store them into a list
def photoInstanceList = userInstance ? Photo.findAllByMyUser(userInstance) : []
//Mapping
[userInstance: userInstance, photoInstanceList: photoInstanceList]
photoInstanceList.each {photo ->
if (photoInstance.myFile != "") {
File file = new File(photoInstance.myFile)
zipFile.putNextEntry(new ZipEntry(Photo.title+".jpeg"))
file.withInputStream { i ->
zipFile << i
}
zipFile.closeEntry()
}
}
zipFile.finish()
response.setHeader("Content-disposition", "filename=\"${login}.zip\"")
response.contentType = "application/zip"
response.outputStream << baos.toByteArray()
response.outputStream.flush()
}
I then use this code in the User view to generate a link that calls the function in the user controller. Am I close? Is there some missing piece in my code?
By the way, This is the first question I have ever written on Stack Overflow. I appreciate the time that you have taken to read this entry. If anything is not clear enough, please where I can improve this question. I am using grails 2.1.1
Thank you for your time!!
If the above code has been copied as is here, shouldn't we be using photo.title instead of Photo.title in the below line
zipFile.putNextEntry(new ZipEntry(Photo.title+".jpeg"))

ASP.NET Resource handler mechanism in MVC4

Simple. I want to localize my application.
I've googled for days, and tried a million different approaches to reach my resources.
The only way I've been succesful is by using the standard asp.net folders "App_LocalResource", making the resource files public and giving them a Custom Tool Name. In the view I can then import the Custom Tool Name with #using.
My issue is that the language/resource items arent changing when I change the culture.
Here is how I change it in global.asax:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
CultureInfo ci = (CultureInfo)this.Session["Culture"];
if (ci == null)
{
string langName = "en";
string autoLang = "";
if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
{
autoLang = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
}
if (autoLang == "da")
langName = autoLang;
ci = new CultureInfo(langName);
this.Session["Culture"] = ci;
}
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
So the culture is either da or en. But I noticed that the names of the resource files has to have a specific syntax. There has to be a default (in this case english) with no country/culture code and other that default has be named like reFile.da-DK.resx. It has to have both language and culture code.
I'm affraid the resource handler can recognize my file, because culture is set to "da" and not "da-DK". If I name my da resouce file to resFile.da.resx I cant import the Custom Tool Name which is my resouce files.
What do I do to solve this?
Use the full culture info string, ex:
var info = new CultureInfo("en-US")
Also for best practice move the code out into the Application_BeginRequest method, that's the standard location you'll see this type of code.

resource listing

I writing wicket webapp. I want to:
list all resources - videoPreview in the folder
preview it
add link to show in main preview panel.
I read a lot and look examples about resources, but seems like can't understand smthg. I write such funny code:
RepeatingView rv = new RepeatingView("showVideo");
add(rv);
File vidPrevDir = (new File("data/catalog/"+product+"/videoPreview"));
File[] list = vidPrevDir.listFiles();
for (File file : list) {
final String previewFile = file.getName();
AjaxLink link = new AjaxLink(rv.newChildId()){
#Override
public void onClick(AjaxRequestTarget target) {
container.name="iframe";
container.attrs.clear();
container.attrs.put("class", "viewPanel");
container.attrs.put("allowfullscreen", "yes");
container.attrs.put("src", "http://www.youtube.com/embed/"+previewFile.substring(previewFile.indexOf("___"), previewFile.length()-4));
target.add(container);
}
};
rv.add(link);
link.add(new Image("videoPreview", product+"/videoPreview/"+file.getName()));
}
In application i call
getResourceSettings().addResourceFolder("data");
It's work, but i feel bad when i see that. So my question is how to make such things in wicket? Maybe there is resource listing or java.io.File->wicket.Image converter ?
I only found built-in method:
ServletContext context = WicketApplication.get().getServletContext();
Set productList = context.getResourcePaths("/catalog");
It list filenames, not resources, but it is preferable approach, then i use in question.

Resources