i am new to Java but have 3 years experience in C#, i am encountering an issue where by a String is not retaining its assigned value (using Getter/Setter methods).
my object class is looking like so;
public class filePathPojo {
private String FilePath;
public void setFilePath(String _Path){
this.FilePath = _Path;
}
public String getFilePath(){
return this.FilePath;
}
}
I am having a separate class file with two methods, one is creating a Directory Route with unique value based on who is using application, it is then storing the Path using the Set, the next method is capturing a screenshot and moving to the new directory. Everytime the screenshot method is running and calling the 'Get' it is returning NULL! this is quite frustrating for something so simple.
other class looks like so
public class folderSetup extends filePathPojo {
public void SetupDirectory(String ScenarioName){
String Root = "C:\\Users\\" + SomeIdentifier + "\\GherkinEvidence\\SomeProject\\";
String Today = DateTime.now().toString("dd:MM:yyyy");
Today = Today.replace(":", "-");
String dtNOW = DateTime.now().toString("HH:mm:ss");
dtNOW = dtNOW.replace("/", "-").replace(":", "");
File file = new File(Root + Today + "\\" + dtNOW + " " + ScenarioName);
boolean dirCreated = file.mkdirs();
System.out.println("***Attemping To Create Directory: " + file.getAbsolutePath());
FilePath = file.getAbsolutePath();
setFilePath(FilePath);
}
public String takeScreenshot(String screenshotName, WebDriver driver){
String path = getFilePath();
System.out.print("Filepath for screenshot picked up is" + path);
try {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
//path = "./target/screenshots/" + source.getName();
FileUtils.copyFile(source, new File(path + "\\" + screenshotName + ".png"));
}
catch(IOException e) {
//path = "Failed to capture screenshot: " + e.getMessage();
}
return path;
}
}
please done anybody have an ideas?
method calls here;
contained i Step Definitions #Before (FolderSetup)
Public Class PerformanceSteps{
#Inject private folderSetup folderSetup;
#Before
public void FolderSetup(Scenario scenario){
System.out.print("***Performing Evidence Directory Setup***");
System.out.println("ScenarioName = " + scenario.getName().toString() + "**");
folderSetup.SetupDirectory(scenario.getName());
}
}
public class Navigate extends BasePage {
#Inject private com.test.utilities.folderSetup folderSetup;
public void toAppianHomePage(){
System.out.println("Navigating to Appian URL " + LoadProperties.Appian_URL);
driver.navigate().to(LoadProperties.Appian_URL);
driver.manage().window().maximize();
folderSetup.takeScreenshot("Navigate Appian Home", driver);
}
Related
I make a plugin for my Minecraft Server and everything works well.
I use a users.yml file to store some data for every user like the groups and uuid.
Something weird is happening now, and I don't know how to solve it:
My users.yml is generating fine, no problems. All data is saved in there and I can access it.
BUT when I try to edit for example the group of the user from the default (this is the group that's assigned to every new user) to admin in the file itself and the user is joining again, the file overwrites the group to default.
What do I not see in the codes below to prevent the overwrite or did I do something wrong?
This is the function that creates the users.yml file:
public class UserList {
private static File usersFile;
private static FileConfiguration usersConf;
public static void Setup(){
usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try {
usersFile.createNewFile();
} catch (Exception e){
System.out.println("Error creating Usersfile: " + e);
}
}
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
public static FileConfiguration get(){
return usersConf;
}
public static void Save(){
try {
usersConf.save(usersFile);
} catch (Exception e){
System.out.println("Error saving Usersfile: " + e);
}
}
public static void reload(){
usersConf = YamlConfiguration.loadConfiguration(usersFile);
}
}
This is the code in the onEnabled() function:
#Override
public void onEnable() {
instance = this;
if (!getDataFolder().exists()) getDataFolder().mkdir();
//Erstelle users.yml mit Standardwerten
UserList.Setup();
UserList.get().addDefault("groups.admin.prefix", "§c");
UserList.get().addDefault("groups.vip.prefix", "§6");
UserList.get().addDefault("groups.default.prefix", "§7");
UserList.get().options().copyDefaults(false);
UserList.Save();
//Hole alle Usergruppen
Set<String> groups = UserList.get().getConfigurationSection("groups").getKeys(false);
//Events Registrieren
getServer().getPluginManager().registerEvents(this, this);
}
And here is the code that executes when a player is joining on the server:
#EventHandler
public void onJoin(PlayerJoinEvent e){
Player p = e.getPlayer();
if (UserList.get().get("users." + p.getName() + ".group") == null){ //<- I tried to prevent it with this if-statement but the problem must be elsewhere
UserList.get().set("users." + p.getName() + ".group", "default");
}
UserList.get().set("users." + p.getName() + ".uuid", p.getUniqueId().toString());
UserList.Save();
if (!p.hasPlayedBefore()) e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is new on this Server!");
else e.setJoinMessage(ChatColor.YELLOW + p.getName() + ChatColor.WHITE + " is " + ChatColor.GREEN + "Online");
}
It's thie line that create the issue:
UserList.get().options().copyDefaults(false);
You should use saveDefaultConfig() which will write the config if (and only if) the config file doesn't exist.
This method should be call with your plugin instance, and will works with your config.yml file.
If you want to copy a file when it doesn't exist, you should do like that :
File usersFile = new File(Main.getInstance().getDataFolder(), "users.yml");
if(!usersFile.exists()){
try (InputStream in = pl.getResource("users.yml");
OutputStream out = new FileOutputStream(usersFile)) {
ByteStreams.copy(in, out);
} catch (Exception e) {
e.printStackTrace();
}
}
config = YamlConfiguration.loadConfiguration(usersFile);
I'm creating an application that uses web view to load the website and allow to download data like IMG/PDF/GIF. The problem is that the download link is not a normal link it's blob:.
I know blob: URL does not refer to the data that exists on the server, it refers to data that your browser currently has in memory.
class DownloadBlobFileJSInterface {
private Context mContext;
private DownloadGifSuccessListener mDownloadGifSuccessListener;
public DownloadBlobFileJSInterface(Context context) {
this.mContext = context;
}
public static String getBase64StringFromBlobUrl(String blobUrl) {
if (blobUrl.startsWith("blob")) {
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + blobUrl + "', true);" +
"xhr.setRequestHeader('Content-type','image/gif');" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobFile = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobFile);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" Android.getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
public void setDownloadGifSuccessListener(DownloadGifSuccessListener listener) {
mDownloadGifSuccessListener = listener;
}
#JavascriptInterface
public void getBase64FromBlobData(String base64Data) {
convertToGifAndProcess(base64Data);
}
private void convertToGifAndProcess(String base64) {
ContextWrapper wrapper = new ContextWrapper(mContext);
String fullPath =wrapper.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
File gifFile = new File(fullPath+ "/File_" + System.currentTimeMillis() + "_.gif");
saveGifToPath(base64, gifFile);
Toast.makeText(mContext, "Downloaded", Toast.LENGTH_SHORT).show();
if (mDownloadGifSuccessListener != null) {
mDownloadGifSuccessListener.downloadGifSuccess(gifFile.getAbsolutePath());
}
}
private void saveGifToPath(String base64, File gifFilePath) {
try {
byte[] fileBytes = Base64.decode(base64.replaceFirst(
"data:image/gif;base64,", ""), 0);
FileOutputStream os = new FileOutputStream(gifFilePath, false);
os.write(fileBytes);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public interface DownloadGifSuccessListener {
void downloadGifSuccess(String absolutePath);
}
}
I want to download the file in device storage.
Is there any way to get data from the blob: URL?
Or
Is it possible to send that data to chrome to download.
I know there is a lot of questions out there like this, this on StackOverflow, I almost tried all but didn't find any of these working.
For each execution screenshots should be saved in different folder with date and time. Tried with below code but its not working as expected.It is generating folder based on minutes not on Execution.Please help..Thanks in advance.
public static String screenShot(WebDriver driver,
String screenShotName, String testName) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
SimpleDateFormat formater1 = new SimpleDateFormat("dd_MM_yyyy_hh_mm");
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File targetFile = new File("iWealthHKTestAutomation/resources/Screenshots_"+formater1.format(calendar.getTime())+"/"+ screenShotName+formater1.format(calendar.getTime()) + ".png");
FileUtils.copyFile(screenshotFile, targetFile);
return screenShotName;
} catch (Exception e) {
System.out.println("An exception occured while taking screenshot " + e.getCause());
return null;
}
}
public String getTestClassName(String testName) {
String[] reqTestClassname = testName.split("\\.");
int i = reqTestClassname.length - 1;
System.out.println("Required Test Name : " + reqTestClassname[i]);
return reqTestClassname[i];
}
enter image description here
If I understood you correctly you call screenShot multiple times during one "run". So if you want the folder to have the "execution time" or rather the start time of the run, you have to pass that as a parameter as well. Otherwise screenShot() will always create a new timestamp.
So change the signature to
public static String screenShot(WebDriver driver,
String screenShotName, String testName, Date startTime) {...
and use startTime instead of the Calendar object.
You have to add testname in folder as it will track execution
If you use timestamp then it will change for same test also
public static String screenShot(WebDriver driver,String screenShotName, String
testName) {
try {
File screenshotFile = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
File targetFile =
new File("iWealthHKTestAutomation/resources/Screenshots_"
+ testName /* pass testname param here like this*/
+ "/"
+ screenShotName
+ String.valueOf(new
SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()))
+ ".png");
FileUtils.copyFile(screenshotFile, targetFile);
return screenShotName;
} catch (Exception e) {
System.out.println("An exception occured while taking screenshot " + e.getCause());
return null;
}
}
Simultaneously, I want to display a extended report on eclipse window(which is come after refreshing project)and mentioned driver(eg. d:/project name/...) using selenium webdriver
This is my Extend report #BeforeTest method
#BeforeTest
public void setUp1() {
// where we need to generate the report
String fileName = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
htmlReporter = new ExtentHtmlReporter("C:/xampp/htdocs/Automation_report/files/summerrentals/summerrentals("+fileName+").html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// Set our document title, theme etc..
htmlReporter.config().setDocumentTitle("Testing");
htmlReporter.config().setReportName("Testing");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
Its after Medhod for attached screenshot
#AfterMethod
public void setTestResult(ITestResult result) throws IOException {
String screenShot = CaptureScreenShot.captureScreen(wd, CaptureScreenShot.generateFileName(result));
if (result.getStatus() == ITestResult.FAILURE) {
test.log(Status.FAIL, result.getName());
test.log(Status.FAIL,result.getThrowable());
test.fail("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
} else if (result.getStatus() == ITestResult.SUCCESS) {
test.log(Status.PASS, result.getName());
test.pass("Screen Shot : " + test.addScreenCaptureFromPath(screenShot));
} else if (result.getStatus() == ITestResult.SKIP) {
test.skip("Test Case : " + result.getName() + " has been skipped");
}
extent.flush();
wd.quit();
}
This is my CaptureScreenShot class for taking screenshot
public class CaptureScreenShot {
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd SSS");
public static String captureScreen(WebDriver driver, String screenName) throws IOException{
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest ="C:/xampp//htdocs/Automation_report/Test-ScreenShots"+screenName+".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
public static String generateFileName(ITestResult result){
Date date = new Date();
String fileName = result.getName()+ "_" + dateFormat.format(date);
return fileName;
}
}
Hope It will help you
May be you want the report to be created in the drive/folder d:/project name/...
// start reporters
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("d://testproject/extent.html");
// create ExtentReports and attach reporter(s)
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
This will create the extent report in the folder/drive d://testproject. I have assumed the project name is testproject here.
Skip to EDIT1 for updated info
What I am trying to achieve:
- I have two classes in my project, a Communicator which communicates with the third party API and the main class that I use to translate the info I receive from the communicator.
My question is: What do I need to do to get my "ds.config" file, which I'm passing as a string, to get loaded? That is if that is even the problem here.
Another Question is: How could I debug this to figure out what is going wrong?
First step is I "initialize my communicator" in the Main.java file:
try{
mDSC = Communicator.createDSCommunicator("ds.config", gRecordDevice, gPlaybackDevice);
} catch (IOException e1) {
// Failed
}
Inside of Communicator this looks like:
public static Communicator createDSCommunicator(String dsConfigFile, String captureMixerName, String playerMixerName) throws IOException {
DSRecognizer dsRecognizer = new DSRecognizer();
dsRecognizer.setInitInfo(dsConfigFile); //THIS LINE CAUSES PROBLEM
// Only applies if setting a filter
dsRecognizer.setLanguage(Language.ENGLISH);
DLog.setLogger(new DLogInterface() {
#Override
public void w(String s, String s2) {
System.out.println("DS log Warning s:" + s + " s2:" + s2);
}
#Override
public void v(String s, String s2) {
System.out.println("DS log Verbose s:" + s + " s2:" + s2);
}
#Override
public void e(String s, String s2) {
System.out.println("DS log Error s:" + s + " s2:" + s2);
}
#Override
public void i(String s, String s2) {
System.out.println("DS log Info s:" + s + " s2:" + s2);
}
#Override
public void d(String s, String s2) {
System.out.println("DS log Debug s:" + s + " s2:" + s2);
}
});
return new Communicator(dsRecognizer, captureMixerName, playerMixerName);
}
Now is where it kinda gets out of my hands, dsRecognizer is a C++ file from the API. This is the code:
public void setInitInfo(String infoFile) throws FileNotFoundException, IOException {
if(this.isInitialized()) {
SLog.v("DSRecognizer", "setInitInfo returning; can only be called prior to init()");
} else {
SLog.v("DSRecognizer", "Info file " + infoFile);
Properties p = new Properties();
FileInputStream fin = null;
try {
fin = new FileInputStream(infoFile); //It doesn't get past this line
p.load(fin);
} finally {
if(fin != null) {
try {
fin.close();
} catch (IOException var13) {
;
}
}
}
File f = new File(infoFile);
File parent = f.getParentFile();
String path = ".";
if(parent != null) {
path = parent.getAbsolutePath();
}
SLog.v("DSRecognizer", "Setting base directory: " + path);
this.mBaseDirectory = path;
if(!p.containsKey("SamplingRate")) {
p.setProperty("SamplingRate", Integer.toString(16000));
}
this.mSamplingRate = Integer.parseInt(p.getProperty("SamplingRate"));
this.mUrlAudio = new URLAudio(this.mSamplingRate);
if(p.containsKey("Parameters")) {
this.mParameters = p.getProperty("Parameters");
} else {
if(!p.containsKey("parameters")) {
throw new FileNotFoundException("parameters file not specified in info file");
}
this.mParameters = p.getProperty("parameters");
p.remove("parameters");
p.setProperty("Parameters", this.mParameters);
}
SLog.v("DSRecognizer", "parameters file set to: " + this.mParameters);
this.mGrammar = null;
if(p.containsKey("Grammar")) {
this.mGrammar = p.getProperty("Grammar");
} else if(p.containsKey("grammarentry")) {
this.mGrammar = p.getProperty("grammarentry");
p.remove("grammarentry");
p.setProperty("Grammar", this.mGrammar);
}
SLog.v("DSRecognizer", "default grammar entry set to: " + this.mGrammar);
if(!p.containsKey("RecognizerType")) {
boolean rescore = false;
if(p.containsKey("Rescore")) {
rescore = Boolean.parseBoolean(p.getProperty("Rescore"));
} else if(p.containsKey("rescore")) {
rescore = Boolean.parseBoolean(p.getProperty("rescore"));
}
if(rescore) {
p.setProperty("RecognizerType", "rescore");
} else {
p.setProperty("RecognizerType", "plain");
}
}
p.remove("Rescore");
p.remove("rescore");
this.mRecognizerType = p.getProperty("RecognizerType");
SLog.v("DSRecognizer", "recognizer type (plain|rescore|dnn) set to: " + this.mRecognizerType);
this.mEpParameters = "";
if(p.containsKey("EPParameters")) {
this.mEpParameters = p.getProperty("EPParameters");
} else if(p.containsKey("epparameters")) {
this.mEpParameters = p.getProperty("epparameters", "");
p.remove("epparameters");
p.setProperty("EPParameters", this.mEpParameters);
}
this.mEpGrammar = "";
if(p.containsKey("EPGrammar")) {
this.mEpGrammar = p.getProperty("EPGrammar");
} else if(p.containsKey("epgrammarentry")) {
this.mEpGrammar = p.getProperty("epgrammarentry", "");
p.remove("epgrammarentry");
p.setProperty("EPGrammar", this.mEpGrammar);
}
StringBuffer sb = new StringBuffer();
Enumeration en = p.keys();
while(en.hasMoreElements()) {
String key = (String)en.nextElement();
sb.append(key);
sb.append(" ");
sb.append(p.getProperty(key));
sb.append("\n");
}
this.mInitString = sb.toString();
SLog.v("DSRecognizer", "DS initialization config: " + this.mInitString);
}
}
Somewhere my "ds.config" file, which is in the assets folder of my android studio project, is not being recognized.
Communicator.createDSCommunicator exits after the line marked with the comment "This line causes problem"
I tried loading the file the same way it's done in dsRecognizer in my main java file, tried loading it using just plain File a = new File().
My question is: What do I need to do to get my "ds.config" file, which I'm passing as a string, to get loaded? That is if that is even the problem here.
Another Question is: How could I debug this to figure out what is going wrong?
EDIT1
Figured out what the problem is: My "ds.config" file is not being located and is giving the error "android.system.ErrnoException: open failed: ENOENT (No such file or directory)".
The file "ds.config" is located in the assets folder of my Android Studio project and any path I provide as a string input to my initializeDS() method causes this error. I need to pass a string to the API file to load the config file but what string do I pass?
Also interested in finding out if there is any other way I can acheive this?