How to read a file in Groovy into a string, without knowing the path to the file? - string

In extension to this question.
Is it possible to read a file into a string without knowing the path to the file? - I only have the file as a 'def'/type-less parameter, which is why I can't just do a .getAbsolutePath()
To elaborate on this, this is how I import the file (which is from a temporary .jar file)
def getExportInfo(path) {
def zipFile = new java.util.zip.ZipFile(new File(path))
zipFile.entries().each { entry ->
def name = entry.name
if (!entry.directory && name == "ExportInfo") {
return entry
}
}
}

A ZipEntry is not a file, but a ZipEntry.
Those have almost nothing in common.
With def is = zipFile.getInputStream(entry) you get the input stream to the zip entry contents.
Then you can use is.text to get the contents as String in the default platform encoding or is.getText('<theFilesEncoding>') to get the contents as String in the specified encoding, exactly the same as you can do on a File object.

Related

How to print the directory which is 1 level up in groovy?

May I know how to print the directory path which is 1 level up? (eg. the groovy file is located in "abc/def/ghi/dummy.groovy" and I want to get the "abc/def" path)
here is my dummy.groovy script
File fileCon= new File("/../")
logger.debug((String.format("[%s]", fileCon))
groovy file could be loaded from plain file, from jar, from url.
i'd not recommend to use this approach - it will not work for all cases.
def url = this.getClass().getProtectionDomain().getCodeSource()?.getLocation()
println new URL(url, '..')
Here is how you get the parent directory as File:
def file = new File('abc/def/ghi/dummy.groovy')
println "Parent: ${file.getParentFile().absolutePath}"
it will give you abc/def/ghi/. You may get parent folder from the result:
println "Parent: ${file.getParentFile().getParentFile().absolutePath}"
you'll get your desired abc/def.
I didn't see any File in GroovyDocs, so I presume this is a Java Class.
So why not just use:
def file = new File('abc/def/ghi/dummy.groovy')
def filePath = file.getParent().getParent()

How to read a json file in web2py using python code and return the dictionaries inside the json file?

def a():
import json
path=open('C:\\Users\\Bishal\\code\\57.json').read()
config=json.load(path)
for key in config:
return key
You have already read the file path=open('C:\Users\Bishal\code\57.json').read(), so when you try to load with json.load(path), the file pointer is at the end of the file; hence nothing gets loaded or parsed.
Either load the file directly into json, or read the contents and then parse the string with json.loads (note the s)
Option 1:
path = open(r'C:\Users\Bishal\code\57.json').read()
config = json.loads(path)
Option 2:
path = open(r'C:\Users\Bishal\code\57.json')
config = json.load(path)
path.close()
Then you can do whatever you like with the result:
for key,item in config.items():
print('{} - {}'.format(key, item))

Creating automatic folder and files in soapui

I wrote a groovy script in soapui to create files in certain location in my pc. How can I make it dynamic and enable the user to write the location the files are saved to by write the location in configuration file imported at test suite level.
if(context.expand('${#Project#ProduceReports}') == 'true') {
def resultDir = new File("D:\\Reports");
if(!resultDir.exists()) {
resultDir.mkdirs();
}
def resultsFile = new File(resultDir, "CSVReport.csv");
}
If you want to get the path from a testSuite property, you can do it as you do with the project property, using context.expand:
def yourPath = context.expand('${#TestSuite#pathDirectory}')
Or alternatively you can do the same with:
def yourPath = context.testCase.testSuite.getPropertyValue('pathDirectory')
Maybe this is out of scope for your question, but could be helpful. If you need you can also use UISupport to ask the user to enter the path he wants with the follow code:
def ui = com.eviware.soapui.support.UISupport;
// the prompt question, title, and default value
def path = ui.prompt("Enter the path","Title","/base/path");
log.info path
This shows:
Define project level custom property REPORT_PATH with value D:/Reports/CSVReport.csv i.e., full path including file and path separate by / slash even on windows platform.
Then use the below script to write the data.
//Define the content that goes as report file. Of course, you may change the content as need by you
def content = """Name,Result
Test1,passed
Test2,failed"""
//Read the project property where path is configured
def reportFileName = context.expand('${#Project#REPORT_PATH}')
//Create file object for reports
def reportFile = new File(reportFileName)
//Create parent directories if does not exists
if (!reportFile.parentFile.exists()) {
reportFile.parentFile.mkdirs()
}
//Write the content into file
reportFile.write(content)

How to get files by using index of List files in groovy

I got the List of all files by using but it give all files , I need specific files from list.
import groovy.io.FileType
def list = []
def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
list.each {
println it.path
}
The method File.eachFileRecurse(FileType, Closure) can only filter by FileType; the options being FILES, DIRECTORIES, and ANY (everything). Keep in mind this is file type in the filesystem sense, and has nothing to do with the file contents. For instance, an HTML document and a PNG image are both FILES.
If you want to filter by, say, the file extension, you can use File.traverse(Map, Closure):
import groovy.io.FileType
def list = []
def dir = new File("source")
dir.traverse(type: FileType.FILES, nameFilter: ~/.*\.html/) { list << it }
list.each {
println it.path
}
In the example above, I used the nameFilter option to specify a regular expression to filter the file name by. You can about the other available options in the documentation.

How read all files in the folder and replace the pattern in file using Groovy

import groovy.io.FileType
import java.io.File;
def list = []
def dir = new File("C:\\Users\\Desktop\\CodeTest")
dir.eachFileRecurse (FileType.FILES)
{
file ->list << file
}
list.each
{
println it.path
}
//Replace the pattern in file and write to file sequentially.
def replacePatternInFile(file, Closure replaceText)
{
file.write(replaceText(file.text))
}
def file = new File(file)
def patternToFind1 = ~/</
def patternToFind2 = ~/>/
def patternToReplace1 = '&lt'
def patternToReplace2 = '&gt'
//Call the method
replacePatternInFile(file){
it.replaceAll(patternToFind1,patternToReplace1)
}
replacePatternInFile(file){
it.replaceAll(patternToFind2,patternToReplace2)
}
println file.getText()
I am able to change the pattern for one file but I want to read all the files in the folder and replace the pattern in each file one by one
while executing it:
ERROR:An error occurred [Could not find matching constructor for: java.io.File(java.util.ArrayList)], see error log for details
You have many problems with your code...
1) You don't need to import:
import java.io.File;
2) When you call:
def file = new File(file)
There is no variable called file in new File(file) (did you mean files?)
3) If you did mean new File(files) then that is where your error is... You can't make a new file from a list of Strings
4) The entity for > is > NOT &gt... The same for < (it needs a semicolon at the end)
You will need to iterate your list of Strings (files.each { path -> ?) and then work on each one in turn.
Though 2) and 3) make me suspect that the above code isn't your real code, but a pretend copy from memory (or a badly redacted copy), as the above code will not give you the error you say you're getting

Resources