java.nio.file.FileSystemException when I move a file - javafx

I'm trying to move image files from beforePath to afterPath, and below is my Code
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class ImageClass {
String fileName, beforePath, afterPath;
void moveFile() {
afterPath = afterPath + "\\" + fileName;
beforePath = beforePath + "\\" + fileName;
System.out.println(beforePath + " ,and, " + afterPath);
Path movefrom = FileSystems.getDefault().getPath(beforePath);
Path target = FileSystems.getDefault().getPath(afterPath);
try {
Files.move(movefrom, target, REPLACE_EXISTING);
} catch (IOException e) {
System.err.println(e);
}
}
}
however the code returns java.nio.file.FileSystemException to me and it says that another process is already using the file. I tried many ways but I can't. How can I fix it?

Related

Testing JavaCC on a File?

So after I compile my code, I want it to read input from a file instead of the command line.
So instead of doing this:
javacc Ex.jj
javac *.java
java Ex "x+2"
I want to do this:
javacc Ex.jj
javac *.java
java test.txt
Where test.txt has this in it:
"x+4"
You can declare a class with a main method in your syntax file:
options {
STATIC = false;
IGNORE_CASE = false;
}
PARSER_BEGIN(Ex)
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Ex {
public static void main(String[] args) {
try (InputStream in = new FileInputStream(args[0])) {
Ex parser = new Ex(in, "UTF-8");
double r = parser.expr();
System.out.println("Result: " + r);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
PARSER_END(Ex)
...
SKIP : { " " | "\r" | "\n" | "\t" }
TOKEN: {
...
}
double expr(): {
}
{
...
}

Extent Report showing only one test case result when executing cucumber scripts in parallel using Cucable plugin

I have to generate Extent Report from all executed test scripts. I am running scripts in parallel. When I use TestNG or Selenium Grid for parallel execution, in those implementation, Extent Reports are getting generated perfectly covering each executed test scripts. But when I run scripts in parallel using Cucable Plugin, Extent report gets generated but would have only 1 test case report if 2 test cases were there in execution.
I am using Cucumber (Selenium), Junit Suite Runner, Cucable Plugin
I verified Extent Report code is thread safe. So not sure, why only in case of Cucable Plugin, Extent report gets only 1 test case. Someone told me, In case of testNG, testNG itself provides additional thread safe mechanism which helps internally to have all executed test cases in report.
ExtentTestManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.IOException;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.Markup;
import com.aventstack.extentreports.markuputils.MarkupHelper;
public class ExtentTestManager {
public static ThreadLocal<ExtentTest> testReport = new ThreadLocal<ExtentTest>();
static ExtentReports extent = ExtentManager.getReporter();
public static synchronized ExtentTest getTest() {
return testReport.get();
}
public static synchronized void setTest(ExtentTest tst)
{
testReport.set(tst);
}
public static synchronized void logInfo(String message) {
testReport.get().info(message);
}
public static synchronized void logPass(String message) {
testReport.get().pass(message);
}
public static synchronized void scenarioPass() {
String passLogg = "SCENARIO PASSED";
Markup m = MarkupHelper.createLabel(passLogg, ExtentColor.GREEN);
testReport.get().log(Status.PASS, m);
}
public static synchronized void logFail(String message) {
testReport.get().fail(message);
}
public static synchronized boolean addScreenShotsOnFailure() {
ExtentManager.captureScreenshot();
try {
testReport.get().fail("<b>" + "<font color=" + "red>" + "Screenshot of failure" + "</font>" + "</b>",
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
}
String failureLogg = "SCENARIO FAILED";
Markup m = MarkupHelper.createLabel(failureLogg, ExtentColor.RED);
testReport.get().log(Status.FAIL, m);
return true;
}
public static synchronized boolean addScreenShots() {
ExtentManager.captureScreenshot();
try {
testReport.get().info(("<b>" + "<font color=" + "green>" + "Screenshot" + "</font>" + "</b>"),
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static synchronized ExtentTest startTest(String testName) {
return startTest(testName, "");
}
public static synchronized ExtentTest startTest(String testName, String desc) {
ExtentTest test = extent.createTest(testName, desc);
testReport.set(test);
return test;
}
}
ExtentManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import com.jacksparrow.automation.utilities.DriverManager;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentManager {
static ExtentReports extent;
static Date d = new Date();
static String fileName = "Extent_" + d.toString().replace(":", "_").replace(" ", "_") + ".html";
public synchronized static ExtentReports getReporter() {
if (extent == null) {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/target/extent-report/"+fileName);
htmlReporter.loadXMLConfig(".\\src\\test\\resources\\extent-config.xml");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
//htmlReporter.setAppendExisting(true);
extent = new ExtentReports();
extent.setAnalysisStrategy(AnalysisStrategy.TEST);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Automation Analyst", "Robin Tyagi");
extent.setSystemInfo("Organization", "Way2Automation");
extent.setSystemInfo("Build no", "W2A-1234");
}
return extent;
}
public static String screenshotPath;
public static String screenshotName;
static int i=0;
public static void captureScreenshot() {
i = i + 1;
File scrFile = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.FILE);
Date d = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("E dd MMM HH:mm:ss z yyyy");
String strDate = formatter.format(d);
screenshotName = strDate.replace(":", "_").replace(" ", "_") + "_"+i+".jpg";
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/extent-report/" + screenshotName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createExtentReportDirectory() {
File file = new File(System.getProperty("user.dir") + "/target/extent-report/");
if (!file.exists()) {
if (file.mkdir()) {
} else {
}
}
}
}
Please help me to understand what could be the correct thought in order to generate Extent Report having summary of all executed test scripts when Cucable Plugin is used for achieving parallel execution in Cucumber (Selenium)
After migrating to cucumber 4.0, I am able to generate single consolidated extent report. Thank you.

URI can`t be null exception on http call after java 8 upgrade

I am getting the following exception after we upgraded our Java version from 6 to 8 on WebSphere 8.5. the following is my code
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.logging.Level;
try {
cicsRecord = setLength(callData).trim();
Date callTime = new Date();
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, callTime.getTime() + " http://"
+ cicsIp + ":" + cicsPort + callData);
}
URL url = new URL("http", cicsIp, cicsPort, callData);
URLConnection connection = url.openConnection();
InputStream istream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(istream));
data = bufferedReader.readLine();
if (_logger.isLoggable(Level.INFO)) {
_logger.log(Level.INFO, "Return from Cics Data =" + data);
}
// this next line removes the headder info that mainframe requires
// to be returned.
responseData = new StringBuffer(data.substring(56));
while ((data = bufferedReader.readLine()) != null) {
responseData.append(data);
}
} catch (Exception e) {
throw new CicsException(e);
}
return responseData.toString();
}
private String setLength(String arg){
StringBuilder dataBuilder = new StringBuilder();
Integer length = new Integer(arg.length() - 100);
String stringLength = new String(length.toString());
int i = stringLength.length();
int j = 68;
_logger.log(Level.INFO, "arg Data =" + arg);
dataBuilder.append(arg);
dataBuilder.setCharAt(57,'L');
dataBuilder.setCharAt(58,'E');
dataBuilder.setCharAt(59,'N');
dataBuilder.setCharAt(60,'G');
dataBuilder.setCharAt(61,'T');
dataBuilder.setCharAt(62,'H');
dataBuilder.setCharAt(63,'=');
dataBuilder.setCharAt(64,'0');
dataBuilder.setCharAt(65,'0');
dataBuilder.setCharAt(66,'0');
dataBuilder.setCharAt(67,'0');
dataBuilder.setCharAt(68,'0');
//charLength = stringLength.charAt(5);
while(i > 0) {
dataBuilder.setCharAt(j, stringLength.charAt(i - 1));
j--;
i--;
}
return dataBuilder.toString();
}
the following is the exception trace
Caused by: java.lang.IllegalArgumentException: URI can't be null.
at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:159)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1145)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1045)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:978)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1561)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1489)
at java.net.URLConnection.getContent(URLConnection.java:762)
at java.net.URL.getContent(URL.java:1071)
at com..compcom.eis.HttpCall.callCICS(HttpCall.java:108)
`
the above code is working fine if I switch the web sphere jdk version to java 6, not sure if the URL string is not being interpreted properly with java 8.
I need some help to find the reason behind this, if I cant make http call with java 8, do I have any other option of making a http call
the following are the imports i have

OConcurrentModificationException while adding edges

We're developing a system that we're basing on OrientDB graphs (OrientDB 2.1.3). In the application, we have a thin pojo->graph persistence layer that should do the work properly, but I get OConcurrentModificationException when having multiple threads updating the database.
Here's an example scenario:
Create a Product vertex with edge to Color "Blue"
Simultaneously (while the transaction for creating Product 1 is open) create another Product vertex is created and also adds an edge to Color "Blue".
OConcurrentModificationException is thrown since the version of Color "Blue" vertex is updated. Note that I'm not trying to save or modify the Color "Blue" vertex itself.
As I understood the docs at http://orientdb.com/docs/2.1/Concurrency.html#concurrency-on-adding-edges setting -DridBag.embeddedToSbtreeBonsaiThreshold=-1 should help me avoid my problem, although it still doesn't work.
What am I missing? Is there anything else I can do to avoid this?
Update:
Stacktrace of the exception:
Error on releasing database 'infogileorientdatabasetest' in pool
com.orientechnologies.orient.core.exception.OConcurrentModificationException: Cannot UPDATE the record #40:1 because the version is not the latest. Probably you are updating an old record or it has been modified by another user (db=v34 your=v33)
at com.orientechnologies.orient.core.conflict.OVersionRecordConflictStrategy.checkVersions(OVersionRecordConflictStrategy.java:55)
at com.orientechnologies.orient.core.conflict.OVersionRecordConflictStrategy.onUpdate(OVersionRecordConflictStrategy.java:42)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.checkAndIncrementVersion(OAbstractPaginatedStorage.java:2279)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.doUpdateRecord(OAbstractPaginatedStorage.java:1911)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.commitEntry(OAbstractPaginatedStorage.java:2364)
at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.commit(OAbstractPaginatedStorage.java:1111)
at com.orientechnologies.orient.core.tx.OTransactionOptimistic.doCommit(OTransactionOptimistic.java:609)
at com.orientechnologies.orient.core.tx.OTransactionOptimistic.commit(OTransactionOptimistic.java:156)
at com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.commit(ODatabaseDocumentTx.java:2582)
at com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.commit(ODatabaseDocumentTx.java:2551)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.commit(ONetworkProtocolBinary.java:1221)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:400)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:223)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:77)
Update 2 - test case
I have reproduced the error using this test case. I would be delighted if there's something else I've done wrong to cause the problem... :-)
Update 3 Updated test case with OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1) in a static block.
package se.infogile.persistence.orientdb;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePoolFactory;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.enterprise.channel.binary.OResponseProcessingException;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerConfiguration;
import com.orientechnologies.orient.server.config.OServerConfigurationLoaderXml;
import com.orientechnologies.orient.server.config.OServerNetworkListenerConfiguration;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by heintz on 14/10/15.
*/
public class OrientDBEdgeProblemTest {
static {
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
}
private static OPartitionedDatabasePoolFactory dbPoolFactory = new OPartitionedDatabasePoolFactory(100);
private static Logger logger = LoggerFactory.getLogger(OrientDBEdgeProblemTest.class);
private OServer server = null;
private static ExecutorService executorService = Executors.newFixedThreadPool(10);
private static final String dbName = "edgeproblemtest";
#Test
public void testVersionIncrementError() throws Throwable {
OrientGraph graph = getGraph(dbName);
graph.getRawGraph().setDefaultTransactionMode();
graph.createVertexType("Product");
graph.createVertexType("Color");
graph.createEdgeType("HasColor");
graph.getRawGraph().begin(OTransaction.TXTYPE.OPTIMISTIC);
// graph.begin();
Vertex v1 = graph.addVertex("Color", "name", "Blue");
graph.commit();
graph.shutdown();
char[] alphabet = new char[] {'A','B','C','D','E','F','G'};
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 2; i++) {
int pos = i;
futures.add(executorService.submit(new Callable<Object>() {
#Override
public Object call() throws Exception {
OrientGraph g = getGraph(dbName);
try {
g.begin();
Vertex v2 = g.addVertex("Product", "name", "Product "+alphabet[pos]);
g.addEdge(null, v2, v1, "HasColor");
Thread.sleep(200);
g.commit();
} catch (OConcurrentModificationException ocme) {
logger.error("Exception while saving: ", ocme);
Assert.fail("OConcurrentModificationException");
} finally {
g.shutdown();
}
return null;
}
}));
}
for (Future f : futures) {
f.get();
}
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
}
#AfterSuite
public void tearDown() throws Exception {
logger.info("Shutting down OrientDB");
if (server != null) {
server.shutdown();
}
}
private OrientGraph getGraph(String dbName) {
String _db = "remote:localhost:3424";
String url = _db + "/" + dbName;
ODatabaseDocumentTx db = null;
try {
OPartitionedDatabasePool pool = dbPoolFactory.get(url,
"root",
"admin");
db = pool.acquire();
} catch (OResponseProcessingException | OConfigurationException | OStorageException oce) {
try {
logger.info("creating new database named " + dbName);
System.err.println("Before DB creation");
OServerAdmin serverAdmin = new OServerAdmin(_db).connect(
"root",
"admin"
);
serverAdmin.createDatabase(dbName, "document", "plocal");
serverAdmin.close();
System.err.println("After DB creation");
} catch (IOException ex) {
logger.error("Unable to create database " + dbName, ex);
}
OPartitionedDatabasePool pool = dbPoolFactory.get(url,
"root",
"admin");
db = pool.acquire();
}
return new OrientGraph(db);
}
#BeforeSuite
public void setUpDatabase() throws Exception {
File f = new File(".");
InputStream is = GraphPersistenceServiceTest.class.getResourceAsStream("/orientdb.config");
Assert.assertNotNull(is);
logger.info("Starting OrientDB");
server = OServerMain.create();
OServerConfigurationLoaderXml loaderXml = new OServerConfigurationLoaderXml(OServerConfiguration.class, GraphPersistenceServiceTest.class.getResourceAsStream("/orientdb.config"));
OServerConfiguration oServerConfiguration = new OServerConfiguration(loaderXml);
System.setProperty("ORIENTDB_ROOT_PASSWORD", "admin");
System.setProperty("RUNMODE", "UNITTEST");
OServerNetworkListenerConfiguration networkConfig = oServerConfiguration.network.listeners.iterator().next();
networkConfig.portRange = "3424-3430";
server.setServerRootDirectory("./target/orientdb");
server.startup(oServerConfiguration);
File serverDir = new File("./target/orientdb");
if (serverDir.exists()) {
FileUtils.deleteDirectory(serverDir);
}
serverDir.mkdirs();
File dbDir = new File(serverDir, "databases");
dbDir.mkdirs();
server.activate();
OGlobalConfiguration.dumpConfiguration(System.out);
Thread.sleep(2000);
}
}
Hi that is because when you add edges to the vertex, vertex itself is modified to store this information, but you may work in mode when information about edges is stored in separate object. Merely use property
-DridBag.embeddedToSbtreeBonsaiThreshold=true and you will rid off this exception.

Har file in project src folder not working

I am trying to access the har file from my project src folder and its not working. its not storing the file to the specified path. But when i try to save the file in local drive, i am able to store and get the values from the file.
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
import java.lang.InterruptedException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example {
public static void main(String[] args) {
FirefoxProfile profile = new FirefoxProfile();
File firebug = new File("firebug-1.10.0a11.xpi");
File netExport = new File("netExport-0.8b22.xpi");
try
{
profile.addExtension(firebug);
profile.addExtension(netExport);
}
catch (IOException err)
{
System.out.println(err);
}
// Set default Firefox preferences
profile.setPreference("app.update.enabled", false);
String domain = "extensions.firebug.";
// Set default Firebug preferences
profile.setPreference(domain + "currentVersion", "2.0");
profile.setPreference(domain + "allPagesActivation", "on");
profile.setPreference(domain + "defaultPanelName", "net");
profile.setPreference(domain + "net.enableSites", true);
// Set default NetExport preferences
profile.setPreference(domain + "netexport.alwaysEnableAutoExport", true);
profile.setPreference(domain + "netexport.showPreview", false);
profile.setPreference(domain + "netexport.defaultLogDir", "C:\\Downloads\\_har\\");
WebDriver driver = new FirefoxDriver(profile);
try
{
// Wait till Firebug is loaded
Thread.sleep(5000);
// Load test page
driver.get("http://www.janodvarko.cz");
// Wait till HAR is exported
Thread.sleep(10000);
}
catch (InterruptedException err)
{
System.out.println(err);
}
driver.quit();
}
}
Instead of C:\Downloads\_har\ i need to have it in my src folder.
path = File.join(File.join(Dir.pwd), 'new_har')
if Dir.exists? path
FileUtils.rm_rf(path)
end
Dir.mkdir(path)
profile['extensions.firebug.netexport.defaultLogDir'] = path.gsub('/', '\\')
profile['update_preferences'] = true
You can use above code to save to your source folder.

Resources