Jenkinsfile read file and use in a loop - loops

I have a scripted Jenkins pipeline located in Jenkinsfile in Github repo. I need to read some data and use it for my script, for this I have this piece of code:
def mydata = [‘val1’, ‘val2’]
mydata.each() {
…
}
Now I need to place the data in the .txt file in the same Github repository and read data from that file. The format in the file is:
val1
val2
I tried this way:
def tmpval = readFile file: ‘values.txt'
env.Mydata = tmpval
Mydata.each() {
......
}
but it doesn’t work as expected, I received
“Caused: java.io.NotSerializableException: java.util.ArrayList$Itr”

Resolved:
String[] mydata = new File("${WORKSPACE}/values.txt")
mydata.each {

Related

Xamrin Forms: How to read the details of a file stored in device's external storage?

I have implemented creating a folder and file in the device's external storage and writing data into that file using this thread.
Now I am trying to get the details of the file. For that, I have added a new function in the interface like below.
//Interface
public interface IAccessFile
{
void CreateFile(string text);
Java.IO.File GetFileDetails();
}
//Android implementation
public Java.IO.File GetFileDetails()
{
string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePathDir = Path.Combine(rootPath, "StockPDT");
if (File.Exists(filePathDir))
{
string filePath = Path.Combine(filePathDir, "STOCK.TXT");
Java.IO.File file = new Java.IO.File(filePath);
return file;
}
else
{
return null;
}
}
But the problem is with the interface function part, getting below error":
The type or namespace name 'Java' could not be found (are you missing a using directive or an assembly reference?)
Screenshot:
If I return the file from the android part like above, it is easy to get the file details in the portable project. Instead of File, I try to return the file path, but it is empty. Is there any other way to get the file details other than this?
As per the notes in question, I tried to fetch the file details using its path.
Reference: https://learn.microsoft.com/en-us/answers/questions/319908/xamrin-forms-how-to-read-the-details-of-a-file-sto.html
//Interface
public interface IAccessFile
{
string GetFileDetails();
}
//Android implementation
public string GetFileDetails()
{
string rootPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePathDir = Path.Combine(rootPath, "StockPDT");
if (!File.Exists(filePathDir))
{
Directory.CreateDirectory(filePathDir);
}
string filePath = Path.Combine(filePathDir, "STOCK.TXT");
return filePath;
}
//Main Project:
string path = DependencyService.Get<IAccessFile>().GetFileDetails();
string fileDetails = File.ReadAllText(path);

Is there a way in selenium to upload the last downloaded file with dynamic name?

The problem I am facing is I have a file which is having a dynamic number at the last.
For example: Tax_subscription_124.pdf which changes everytime.
Can I upload this particular file as currently I am downloading it in a particular location but not able to upload the same due to dynamic name?
The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8 or newer due to the lambda expression.
After that
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys(chosenFile);

How to write back to cfg file when I load the file and change the MySpan variate?

I want to write the conf out to myconfig.gcfg, when I load the file and has change the Name string. How should I do?
Sample config:
[Span]
Name = "DuraSpan"
MySpan = 4
[Sys]
SerialName = "/dev/ttyS0"
Go code:
import "gopkg.in/gcfg.v1"
type Config struct {
Span struct {
Name string
MySpan int
}
Sys struct{
SerialName string
}
}
var conf Config
err := gcfg.ReadFileInto(&conf, "myconfig.gcfg")
conf.Span.MySpan = 6
how to write back the change to file?
The library you choose don't do it for now, it has the task into the todo list, according to the documentation.
For the time being you should contact the developer to be aware of when the feature is scheduled, find another library or do it yourself.
You could use the go-yaml package to do it.

How to get last downloaded file using selenium

Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.
Thanks in advance
You can save your download to a fix location by using the profile. Check these discussions:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
As you have mentioned that you have covered the reading part. You can read it from that fixed location.
Below is the code snippet that can help resolve the above query:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as #BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension
Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.
Let say, how we test latest downloaded file in browser.
In existing test browser Open NewTab Window
Go to
downloads (chrome://downloads/)
Check if expected file is there
or not
Now same thing in selenium using java
driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName= element.getText();

Not writing to the file Scala

I have the following code, which is supposed to write to a file one line at a time, until it reaches ^EOF.
import java.io.PrintWriter
import java.io.File
object WF {
def writeline(file: String)(delim: String): Unit = {
val writer = new PrintWriter(new File(file))
val line = Console.readLine(delim)
if (line != "^EOF") {
writer.write(line + "\n")
writer.flush()
}
else {
sys.exit()
}
}
}
var counter = 0
val filename = Console.readLine("Enter a file: ")
while (true) {
counter += 1
WF.writeline(filename)(counter.toString + ": ")
}
For some reason, at the console, everything looks like it works fine, but then, when I actually read the file, nothing has been written to it! What is wrong with my program?
Every time you create a new PrintWriter you're wiping out the existing file. Use something like a FileWriter, which allows you to specify that you want to open the file for appending:
val writer = new PrintWriter(new FileWriter(new File(file), true))
That should work, although the logic here is pretty confusing.
Use val writer = new FileWriter(new File(file), true) instead. The second parameter tells the FileWriter to append to the file. See http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
I'm guessing the problem is that you forgot to close the writer.

Resources