I'm using groovy script in soapUI. I want to save my response to file. I'm using the following script. The file is created, but it's content is empty.
//get dir target from property
def dirTarget = context.expand( '${#Project#SnapShotDirTarget}' )
def fileDir = new File(dirTarget);
if(!fileDir .exists()) {
fileDir .mkdirs()
}
def currentDate = new Date().format("yyyy-MM-dd hh:mm")
def fileName = "Snapshot - "+currentDate+".txt"
def resultsFile= new File(fileDir , context.expand( fileName) )
if(!resultsFile.exists()) {
resultsFile.createNewFile();
}
resultsFile.append("Post URL:"+messageExchange.getEndpoint()+'\n' );
resultsFile.append("Request:"+'\n' );
resultsFile.append(messageExchange.getRequestContent()+'\n' );
resultsFile.append("Response:"+'\n' );
resultsFile.append(messageExchange.getResponseContent()+'\n' );
If you are running Windows the colon between the hour and minutes in the filename is going to cause some problems, since colon is not allowed in Windows file names.
When I tried running the script it created an empty file called "Snapshot - 2014-08-14 09" (everything after and including the colon is missing)
Changing the colon to something else makes the trick.
def currentDate = new Date().format("yyyy-MM-dd hh_mm")
The call to createNewFile is not necessary by the way. The append call will create the file if it doesn't exist.
Related
This is going to be a really stupid question - how do I open a file in the Filing Cabinet and read it in, line by line, using SuiteScript? Every example I can find online seems to start in the middle, taking for granted knowledge that I don't possess.
Is there a simple example somewhere online I've not found? All I need is for it to:
Open file (giving file name and folder)
Read the first line
Read the second line
....
Close the file.
In Suitescript 2.0 use the N/file module. The module can only be used in server side (not client) scripts. Reference Suite Answer Id: 43524 for N/file module and Suite Answer Id: 43520 for Script Types.
require(['N/file', 'N/record'], function(file, record) {
//use file name and folder and 'N/search' module to find the file id if necessary
// load file
var myFile = file.load({
id: '__' //enter the file internal id, absolute or relative file path
})
//get the # of lines
var arrLines = myFile.getContents().split(/\n|\n\r/);
// loop through each line, skipping the header
for (var i = 1; i < arrLines.length - 1; i++) {
//split the 1 line of data into an array. If the file was a csv file, each array position holds a value from the columns of the 1 line of data
var content = arrLines[i].split(',');
// get values from the columns of a CSV file
var column1 = content[0]; //first column
var column2 = content[1]; //second column
//can use the column data above to i.e. create new record and set default value, update existing records, write the data elsewhere
//to check each line for a given value
arrLines[i].includes('keyword'); //returns true or false
}
});
You can get the suitescript api documentation here
https://docs.oracle.com/cloud/latest/netsuitecs_gs/docs.htm
look at the file module
Let's keep it simple:
For SuiteScript 1.0:
var arrLines = nlapiLoadFile({fileinternalid}).getValue().split(/\n|\n\r/);
For SuiteScipt 2.0:
var arrLines = file.load({
id: {fileinternalid}
});
arrLines.getValue().split(/\n|\n\r/);
arrLines.description = 'My CSV File'
var fileId = arrLines.save();
...
// Add additional code
I have created SSRS report and want to change the name of file with adding Date to it. I really appreciate your help.
Already tried https://reportsyouneed.com/ssrs-adding-date-to-exported-filenames/ solution and it doesn't work.
An easy alternative might be
An alternative approach to creating unique files for every delivery is to include a timestamp in the file name. To do this, add the #timestamp variable to the file name (for example, CompanySales#timestamp). With this approach, the file name is unique by definition, so it will never be overwritten.
See https://learn.microsoft.com/en-us/sql/reporting-services/subscriptions/file-share-delivery-in-reporting-services?view=sql-server-ver15
I got a perfect solution for this Issue.
This link works (very well) only if there is no parameter required before export.
Code in this link try to get the file name when you click on the file, means when download not ready and report looking for initial inputs.
But my file has date parameters in the beginning to input.
So I modify the code to wait till download is available and added to the end of "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js" file
function ModifyExportFileName(){
var rv=null;
var r= null;
var today =new Date();
var day= ("0" + today.getDate()).slice(-2);
var month = ("0"+ (today.getMonth() + 1)).slice(-2);
var year = ("0"+ today.getFullYear()).slice(-2);
var text= "DD";
try{
rv=this.$find("ctl31");
r=rv._getInternalViewer();
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
}
catch(err)
{
//console.log(err);
setTimeout(ModifyExportFileName,2000);
return;
}
if(r==null)
{
setTimeout(ModifyExportFileName,2000);
return;
}
else
{
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
var j = url.indexOf("&",i+1);
var oldFileName= url.substring(i+9,j);
var filename=text.concat(year,month,day)
r.ExportUrlBase= url.substring(0,i) + 'FileName=' + filename+ url.substring(j);
}
//console.log(filename);
setTimeout(ModifyExportFileName,2000);
}
ModifyExportFileName();
I need date as a filename so date is added as "filename". you can change it as required
I would like to rename lastModified() json as filename+"processing" in jenkins with groovy. I am unsuccessfully doing :
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
file.renameTo( new File( file.getName() + ".processing") )
print "Filename is : " + file
How to rename it ?
You actually already have the answer in your code, you're just not storing it in a variable! new File( file.getName() + ".processing")
An instance of File isn't the actual entry on the file system, it's just a representation of one. So after you perform the rename, you need to work with the File instance that represents the renamed file system entry:
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
def modifiedFile = new File("${file.getName()}.processing")
/* Check their existence */
println "${file.getName()} exists? ${file.exists()}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
/* Rename the file system entry using the File objects */
file.renameTo(modifiedFile)
/* See what we have */
println "Original filename is: ${file}"
println "${file.getName()} exists? ${file.exists()}"
println "Modified Filename is: ${modifiedFile}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
Update : renameTo is working fine. However file var is not reflecting the rename name. How to get new rename name ?
I move a file to a folder. Is there any way to not overwrite a file with that name?
For example, folder contains a file named: file1.pdf. How can I move another file named: file1.pdf into that folder so that the name get changed to e.g. file1-1.pdf, file1-2.pdf to prevent the original file from getting overwritten.
I'm using substring to do that but it's quite long and awful code.
You could use something like this:
def save = { File dir, String name ->
int version = 1
def splitName = name.split(/\./, 0).with { it -> it.length == 1 ? [it[0], ''] : [it[0..-2].join('.'), ".${it[-1]}"] }
def rename = { String prefix, String ext -> "$prefix-$version$ext" }
while (new File(dir, name).exists()) {
name = rename(*splitName)
version++
}
println "Save the file as $name"
}
save(new File('/tmp'), 'file.txt')
Which assuming you have a file /tmp/file.txt and a file /tmp/file-1.txt already, prints out: Save the file as file-2.txt
I just have a question about writing a function that will search a directory for the most recent log in a directory. I currently came up with one, but I'm wondering if there is a better (perhaps more proper) way of doing this.
I'm currently using hdsentinel to create logs on computer and placing the log in a directory. The logs are saved like so:
/directory/hdsentinel-computername-date
ie. C:/hdsentinel-owner-2010-11-11.txt
So I wrote a quick script that loops through certain variables to check for the most recent (within the past week) but after looking at it, I'm question how efficient and proper it is to do things this way.
Here is the script:
String directoryPath = "D:"
def computerName = InetAddress.getLocalHost().hostName
def dateToday = new Date()
def dateToString = String.format('%tm-%<td-%<tY', dateToday)
def fileExtension = ".txt"
def theFile
for(int i = 0; i < 7; i++) {
dateToString = String.format('%tY-%<tm-%<td', dateToday.minus(i))
fileName = "$directoryPath\\hdsentinel-$computerName-$dateToString$fileExtension"
theFile = new File(fileName)
if(theFile.exists()) {
println fileName
break;
} else {
println "Couldn't find the file: " + fileName
}
}
theFile.eachLine { print it }
The script works fine, perhaps it has some flaws. I felt I should go ahead and ask what the typical route is for this type of thing before I continue with it.
All input is appreciated.
Though a bit messy, you could implement a multi-column sort via the 'groupBy' method (Expounding on Aaron's code)..
def today = new Date()
def recent = {file -> today - new Date(file.lastModified()) < 7}
new File('/yourDirectory/').listFiles().toList()
.findAll(recent)
.groupBy{it.name.split('-')[1]}
.collect{owner, logs -> logs.sort{a,b -> a.lastModified() <=> b.lastModified()} }
.flatten()
.each{ println "${new Date(it.lastModified())} ${it.name}" }
This finds all logs created within the last week, groups them by owner name, and then sorts according to date modified.
If you have files other than logs in the directory, you may first need to grep for files containing 'hdsentinel.'
I hope this helps.
EDIT:
From the example you provided, I cannot determine if the least significant digit in the format:
C:/hdsentinel-owner-2010-11-11.txt
represents the month or the day. If the latter, sorting by file name would automatically prioritize by owner, and then by date created (without all of the chicanery of the above code).
For Instance:
new File('/directory').listFiles().toList().findAll(recent).sort{it.name}
Hopefully this helps some..This sorts a given path by date modified in a groovier way. The lists them out.
you can limit the list, and add other conditions in the closure to get the desired results
new File('/').listFiles().sort() {
a,b -> a.lastModified().compareTo b.lastModified()
}.each {
println it.lastModified() + " " + it.name
}
As I was trying to solve a similar problem, learnt a much cleaner approach.
Define a closure for sorting
def fileSortCondition = { it.lastModified() }
And File.listFiles() has other variation which accepts FileFilter and FilenameFilter in Java, and these interfaces has a single method called accept, Implement the interface as a closure.
def fileNameFilter = { dir, filename ->
if(filename.matches(regrx))
return true
else
return false
} as FilenameFilter
And lastly
new File("C:\\Log_Dir").listFiles(fileNameFilter).sort(fileSortCondition).reverse()
Implement FileFilter interface if filtering is to be done by File attributes.
def fileFilter = { file ->
if(file.isDirectory())
return false
else
return true } as FileFilter