OpenSessionInViewInterceptor Spring WebSocket - spring-websocket

Has anyone implemented OpenSessionInView yet on Spring WebSocket messages yet? I need to implement this and was hoping for some existing material.
I created some test stuff such as below, but I ran into TransactionExceptions, presumably because when you send back a reply, your session needs to cover both sending and receiving messages
public class OpenSessionInViewChannelInterceptor extends ChannelInterceptorAdapter{
#Inject
private SessionFactory sessionFactory;
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
SessionFactory sf = sessionFactory;
if (!TransactionSynchronizationManager.hasResource(sf)) {
// New Session to be bound for the current method's scope...
Session session = openSession();
try {
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
return super.preSend(message, channel);
}
finally {
SessionFactoryUtils.closeSession(session);
TransactionSynchronizationManager.unbindResource(sf);
}
}
else {
// Pre-bound Session found -> simply proceed.
return super.preSend(message, channel);
}
}
protected Session openSession() throws DataAccessResourceFailureException {
try {
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.MANUAL);
return session;
}
catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
}
Exception
[MSA] DEBUG [2016-06-21T18:40:05,054] SimpAnnotationMethodMessageHandler.processHandlerMethodException(468) | Searching methods to handle HibernateException
[MSA] ERROR [2016-06-21T18:40:05,057] SimpAnnotationMethodMessageHandler.processHandlerMethodException(478) | Unhandled exception
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) ~[spring-orm-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.appfuse.dao.hibernate.GenericDaoHibernate.flush(GenericDaoHibernate.java:165) ~[classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_60]
at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_60]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.9.RELEASE.jar:4.1.9.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.1.9.RELEASE.jar:4.1.9.RELEASE]

Related

JUnit test for post Rest WS using rest-assured

I am writing junit for post using rest-assured, and while executing
My Test Class:
public class PolicyResourceTest {
private static MockRESTServer server;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
server = new MockRESTServer(8080, new PolicyResource());
server.start();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
server.stop();
}
#Test
public final void testCreatePolicy() {
Policy policy=new Policy();
policy.setName("policy123");
RestAssured.with()
.contentType("application/json")
.accept("application/json")
.body(policy)
.post("/create")
.then()
.assertThat()
.statusCode(200);
}
My Resource Class:
#Path("/")
public class PolicyResource {
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response test( Policy messageBody) {
System.out.println("policy: "+messageBody);
return Response.ok().status(200).build();
}
}
I am getting below exception:
org.apache.http.NoHttpResponseException: localhost:8080 failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:281)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:257)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:207)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:684)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:486)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.apache.http.client.HttpClient$execute$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at io.restassured.internal.RequestSpecificationImpl$RestAssuredHttpBuilder.doRequest(RequestSpecificationImpl.groovy:2028)
at io.restassured.internal.http.HTTPBuilder.post(HTTPBuilder.java:349)
at io.restassured.internal.http.HTTPBuilder$post$2.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at io.restassured.internal.RequestSpecificationImpl.sendRequest(RequestSpecificationImpl.groovy:1202)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
#Anju Singh, Make sure your back end is working properly.
I tried the request on my local as we as on the mock api and was successfully able to test for Objects as well. The exception you received org.apache.http.NoHttpResponseException: localhost:8080 failed to respond is from the Server. There is no issue from RestAssured or JUnit to resolve.
#Test(enabled=true)
public void sampleTester() {
EnrollEmail email = new EnrollEmail();
email.setEmailAddress("sample#domain.com");
RestAssured.given().contentType(ContentType.JSON).body(email).when().post("https://jsonplaceholder.typicode.com/posts").then()
.assertThat()
.statusCode(201);
}
#Test(enabled=true)
public void sampleTester2() {
EnrollEmail email = new EnrollEmail();
email.setEmailAddress("sample#domain.com");
RestAssured.given().contentType(ContentType.JSON).body(email).when().post("http://localhost:8089/posts").then()
.assertThat()
.statusCode(201);
}

JavaFX with OpenCV start/pause webcam. FXMLLoader

I am trying to learn JavaFX with the library OpenCV for my degree. I want to make a program that detects people. We can name it people counter. I saw some videos already and I want to do that too.
The problem is that I have to start to learn JavaFX and the library OpenCV.
So I started to create a simple project that starts / pause the webcam and take a snapshot. I saw someone on youtube doing this and I started to recreate it.
The problem is that I have this error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
My code is:
Main
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("Camera.fxml"));
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
CameraController
package application;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import javax.imageio.ImageIO;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
public class CameraController {
// definitions
#FXML
private Button btn_start, btn_pause, btn_snapshot;
#FXML
private ImageView imgView;
private DaemonThread myThread = null;
int count = 0;
VideoCapture webSource = null;
Mat frame = new Mat();
MatOfByte mem = new MatOfByte(); /// start button
#FXML
protected void startClick(ActionEvent event) {
webSource =new VideoCapture(0);
myThread = new DaemonThread();
Thread t = new Thread(myThread);
t.setDaemon(true);
myThread.runnable = true;
t.start();
btn_start.setDisable(true);
btn_pause.setDisable(false); // stop button
}
#FXML
protected void pauseClick(ActionEvent event) {}
#FXML
protected void snapshotClick(ActionEvent event) {}
class DaemonThread implements Runnable {
protected volatile boolean runnable = false;
#Override
public void run() {
synchronized (this) {
while (runnable) {
if (webSource.grab()) {
try {
webSource.retrieve(frame);
Imgcodecs.imencode(".bmp", frame, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
BufferedImage buff = (BufferedImage) im;
imgView.setImage(SwingFXUtils.toFXImage(buff, null));
if (!runnable) {
System.out.println("Going to wait()");
this.wait();
}
} catch (Exception ex) {
System.out.println("Error");
}
}
}
}
}
}
/////////////////////////////////////////////////////////
}
}
The problem is on this line:
BorderPane root = (BorderPane) FXMLLoader.load(getClass().getResource("Camera.fxml"));
Scene scene = new Scene(root,400,400);
Full console error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_Mat()J
at org.opencv.core.Mat.n_Mat(Native Method)
at org.opencv.core.Mat.<init>(Mat.java:24)
at application.CameraController.<init>(CameraController.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:927)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:971)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:220)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:744)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at application.Main.start(Main.java:15)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application application.Main
Thank you in advance!
Try this it worked for me nu.pattern.OpenCV.loadShared();
I fixed the problem by just adding System.loadLibrary(Core.NATIVE_LIBRARY_NAME):
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
launch(args);
}

Appium unable to retrieve webelement using TestNG

We have developed an app and we would like to configure automated tests with Appium and TestNG. The app contains both native and web pages, but the header where reside logo, hamburger (in homepage) and back button is always native.
I get the web resources id from Chrome Inspector, but the command:
WebElement usernameEditText = driver.findElement(By.id("username"));
or
WebElement login = driver.findElement(By.xpath("//input[#id='login-ico']"));
fails with this error:
org.openqa.selenium.NoSuchElementException: An element could not be
located on the page using the given search parameters. (WARNING: The
server did not provide any stacktrace information)
Command duration or timeout: 309 milliseconds
For documentation on this error, please visit:
http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.46.0', revision:
'61506a4624b13675f24581e453592342b7485d71', time: '2015-06-04 10:22:50'
System info: host: 'stefano', ip: '127.0.0.1', os.name: 'Mac OS X',
os.arch: 'x86_64', os.version: '10.11.4', java.version: '1.7.0_79'
*** Element info: {Using=xpath, value=//input[#id='login-ico']}
Session ID: 18098de4-ee19-42b5-9f91-30f6f7e01552
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{automationName=Appium, platform=LINUX,
javascriptEnabled=true,
appActivity=com.UnipolSaiApp.activity.MainActivity,
networkConnectionEnabled=true, desired={automationName=Appium,
platformVersion=5.0.1, platformName=Android, deviceName=Android,
appActivity=com.UnipolSaiApp.activity.MainActivity, device=Android,
appPackage=com.UnipolSaiApp}, locationContextEnabled=false,
appPackage=com.UnipolSaiApp, platformVersion=5.0.1,
databaseEnabled=false, deviceName=9b984ca9, platformName=Android,
webStorageEnabled=false, device=Android, warnings={},
takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:605)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:43)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:455)
at io.appium.java_client.DefaultGenericMobileDriver.findElementByXPath(DefaultGenericMobileDriver.java:129)
at io.appium.java_client.AppiumDriver.findElementByXPath(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElementByXPath(AndroidDriver.java:1)
at org.openqa.selenium.By$ByXPath.findElement(By.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:350)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:51)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at pages.LoginPage.login_success(LoginPage.java:25)
at scenarios.AppiumTest.loginTest(AppiumTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.runWorkers(TestRunner.java:1178)
at org.testng.TestRunner.privateRun(TestRunner.java:757)
at org.testng.TestRunner.run(TestRunner.java:608)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1158)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1083)
at org.testng.TestNG.run(TestNG.java:999)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:74)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Instead, the retrieving of native elements occur with success.
Here the code of my AndroidSetup:
public class AndroidSetup {
protected AndroidDriver driver;
protected void prepareAndroidForAppium() throws MalformedURLException {
File appDir = new File("/path_of_apk");
File app = new File(appDir,"*****.apk");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability("deviceName","Android");
dc.setCapability("platformVersion","5.0.1");
dc.setCapability("platformName","Android");
//dc.setCapability(CapabilityType.BROWSER_NAME, "browser");
dc.setCapability("device","Android");
dc.setCapability("appPackage","com.*******");
dc.setCapability("appActivity","com.*******.MainActivity");
//other caps
//dc.setCapability("app",app.getAbsolutePath());
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), dc);
Set<String> contexts = driver.getContextHandles();
for (String ctx : contexts) {
System.out.println(ctx);
}
}
}
Here the AppiumTest:
public class AppiumTest extends AndroidSetup {
#BeforeClass
public void setUp() throws Exception {
prepareAndroidForAppium();
}
#AfterClass
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void loginTest() throws InterruptedException
{
new LoginPage(driver).login_success();
}
}
Here the BaePage class:
public class BasePage {
protected WebDriver driver;
String app_package_name = "com.****:id/";
public BasePage(WebDriver driver) {
this.driver = driver;
}
protected void waitForVisibilityOf(By locator) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
protected void waitForClickabilityOf(By locator) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(locator));
}
}
And here the LoginPage:
public class LoginPage extends BasePage {
public LoginPage(WebDriver driver) {
super(driver);
}
public LoginPage login_success() throws InterruptedException {
Thread.sleep(30000);
WebElement login = driver.findElement(By.xpath("//input[#id='login-ico']"));
login.click();
WebElement usernameEditText = driver.findElement(By.id("usernameET"));
usernameEditText.sendKeys("****");
WebElement passwordEditText = driver.findElement(By.id("passwordET"));
passwordEditText.sendKeys("*****");
WebElement loginButton = driver.findElement(By.id("submitBtn"));
loginButton.click();
return new LoginPage(driver);
}
}
The following code:
Set<String> contexts = driver.getContextHandles();
for (String ctx : contexts) {
System.out.println(ctx);
}
returns just NATIVE_APP entry.
Can you explain me what's wrong? It's an error about the Appium configuration?

SDN:4 Value injection into Converter fails

I wrote a custom converter for my graph property as shown below.
Entity class
#NodeEntity(label = "Person")
public class Person extends AbstractEntity {
#Property(name = "accessCount")
private Long accessCount;
#Property(name = "lastAccessDate")
#Convert(LocalDateTimeConverter.class)
private LocalDateTime lastAccessDate;
public Long getAccessCount() {
return accessCount;
}
public void setAccessCount(final Long accessCount) {
this.accessCount = accessCount;
}
public LocalDateTime getLastAccessDate() {
return lastAccessDate;
}
public void setLastAccessDate(final LocalDateTime lastAccessDate) {
this.lastAccessDate = lastAccessDate;
}
}
Converter
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.ogm.typeconversion.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, String> {
private static final Logger LOG = LoggerFactory.getLogger(LocalDateTimeConverter.class);
#Value("${neo4j.dateTime.format:yyyy-MM-dd HH:mm:ss.SSS}")
private String dateTimeFormat;
#Override
public String toGraphProperty(final LocalDateTime value) {
LOG.debug("Converting local date time: {} to string ...", value);
if (value == null) {
return "";
}
return String.valueOf(value.format(getDateTimeFormatter()));
}
#Override
public LocalDateTime toEntityAttribute(final String value) {
LOG.debug("Converting string: {} to local date time ...", value);
if (StringUtils.isBlank(value)) {
return null;
}
return LocalDateTime.parse(value, getDateTimeFormatter());
}
public DateTimeFormatter getDateTimeFormatter() {
return DateTimeFormatter.ofPattern(dateTimeFormat);
}
}
It's unit test passes
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestContextConfiguration.class)
#DirtiesContext
#TestExecutionListeners(inheritListeners = false, listeners = { DataSourceDependencyInjectionTestExecutionListener.class })
public class LocalDateTimeConverterTest {
public static final String DATE_TIME_VALUE = "2015-06-22 13:05:04.546";
#Autowired
protected LocalDateTimeConverter localDateTimeConverter;
#Test
public void should_get_date_time_formatter() {
final DateTimeFormatter dateTimeFormatter = localDateTimeConverter.getDateTimeFormatter();
assertNotNull(dateTimeFormatter);
}
#Test
public void should_convert_local_date_time_property_from_graph_property_string_for_database() throws Exception {
final LocalDateTime localDateTime = LocalDateTime.of(2015, Month.JUNE, 22, 13, 5, 4, 546000000);
final String actual = localDateTimeConverter.toGraphProperty(localDateTime);
final String expected = localDateTime.format(localDateTimeConverter.getDateTimeFormatter());
assertEquals(expected, actual);
}
#Test
public void should_convert_string_from_database_to_local_date_time() throws Exception {
final LocalDateTime localDateTime = localDateTimeConverter.toEntityAttribute(DATE_TIME_VALUE);
assertNotNull(localDateTime);
assertThat(localDateTime.getDayOfMonth(), equalTo(22));
assertThat(localDateTime.getMonthValue(), equalTo(6));
assertThat(localDateTime.getYear(), equalTo(2015));
assertThat(localDateTime.getHour(), equalTo(13));
assertThat(localDateTime.getMinute(), equalTo(5));
assertThat(localDateTime.getSecond(), equalTo(4));
assertThat(localDateTime.getNano(), equalTo(546000000));
}
}
However, when I'm trying to use it from a repository as shown below.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestContextConfiguration.class)
#DirtiesContext
#TestExecutionListeners(inheritListeners = false, listeners = { DataSourceDependencyInjectionTestExecutionListener.class })
public class PersonRepositoryTest extends AbstractRepositoryTest<CypherFilesPopulator> {
private static final Logger LOG = LoggerFactory.getLogger(PersonRepositoryTest.class);
public static final String CQL_DATASET_FILE = "src/test/resources/dataset/person-repository-dataset.cql";
#Autowired
PersonRepository personRepository;
#Test
public void should_find_all_persons() {
LOG.debug("Test: Finding all persons ...");
final Iterable<Person> persons = personRepository.findAll();
persons.forEach(person -> {LOG.debug("Person: {}", person);});
}
#Override
public CypherFilesPopulator assignDatabasePopulator() {
return DatabasePopulatorUtil.createCypherFilesPopulator(Collections.singletonList(CQL_DATASET_FILE));
}
}
My unit test fails as value injection isn't happening.
org.neo4j.ogm.metadata.MappingException: Error mapping GraphModel to instance of com.example.model.node.Person
at org.neo4j.ogm.mapper.GraphEntityMapper.mapEntities(GraphEntityMapper.java:97)
at org.neo4j.ogm.mapper.GraphEntityMapper.map(GraphEntityMapper.java:69)
at org.neo4j.ogm.session.response.SessionResponseHandler.loadAll(SessionResponseHandler.java:181)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:69)
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:99)
at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:119)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy110.loadAll(Unknown Source)
at org.springframework.data.neo4j.repository.GraphRepositoryImpl.findAll(GraphRepositoryImpl.java:123)
at org.springframework.data.neo4j.repository.GraphRepositoryImpl.findAll(GraphRepositoryImpl.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:475)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:460)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:432)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy124.findAll(Unknown Source)
at com.example.repository.PersonRepositoryTest.should_find_all_persons(PersonRepositoryTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.NullPointerException: pattern
at java.util.Objects.requireNonNull(Objects.java:228)
at java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1571)
at java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:534)
at com.example.converter.LocalDateTimeConverter.getDateTimeFormatter(LocalDateTimeConverter.java:41)
at com.example.converter.LocalDateTimeConverter.toEntityAttribute(LocalDateTimeConverter.java:37)
at com.example.converter.LocalDateTimeConverter.toEntityAttribute(LocalDateTimeConverter.java:14)
at org.neo4j.ogm.entityaccess.FieldWriter.write(FieldWriter.java:64)
at org.neo4j.ogm.mapper.GraphEntityMapper.writeProperty(GraphEntityMapper.java:164)
at org.neo4j.ogm.mapper.GraphEntityMapper.setProperties(GraphEntityMapper.java:129)
at org.neo4j.ogm.mapper.GraphEntityMapper.mapNodes(GraphEntityMapper.java:110)
at org.neo4j.ogm.mapper.GraphEntityMapper.mapEntities(GraphEntityMapper.java:94)
... 74 more
I'm wondering how my converter object is instantiated by SDN4? I can't spot what I'm doing wrong here. Similar approach used to work in SDN 3.4. It started to break when I upgraded to SDN 4.
This is happening because it's not actually Spring that constructs AttributeConverter instances in this case. AttributeConverter comes from the underlying object-graph mapper (OGM) and this, by design, is not Spring-aware and therefore disregards any Spring annotations on classes that it manages.
However, if you change the #Convert annotation on the Person field by specifying the target type instead of the AttributeConverter class then you can use Spring's ConversionService instead. You can register the Spring converter that you want with a MetaDataDrivenConversionService and the framework should use this for the conversion.
Your meta-data-driven conversion service can be constructed in your Neo4jConfiguration subclass like this:
#Bean
public ConversionService springConversionService() {
return new MetaDataDrivenConversionService(getSessionFactory().metaData());
}

Neo4 Example does not work - Class not found

I have copied and pasted a simple neo4j example from the tutorial section but currently i got the messages:
[INFO] Surefire report directory: /home/kama/ws-git/neo4jexample/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNGMapConfigurator#17bd6a1
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 2.995 sec <<< FAILURE!
Results :
Failed tests: firstTest(com.soebes.tutorials.Neo4JAppTest): com/soebes/tutorials/neo4jexample/RelationTypes
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
The detailed error message:
java.lang.NoClassDefFoundError: com/soebes/tutorials/neo4jexample/RelationTypes
at com.soebes.tutorials.neo4jexample.Neo4JApp.createDb(Neo4JApp.java:44)
at com.soebes.tutorials.neo4jexample.Neo4JApp.main(Neo4JApp.java:25)
at com.soebes.tutorials.Neo4JAppTest.firstTest(Neo4JAppTest.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:691)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:883)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1208)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:758)
at org.testng.TestRunner.run(TestRunner.java:613)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:87)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1137)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1062)
at org.testng.TestNG.run(TestNG.java:974)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:76)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeMulti(TestNGDirectoryTestSuite.java:161)
at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:101)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:115)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:103)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:74)
Caused by: java.lang.ClassNotFoundException: com.soebes.tutorials.neo4jexample.RelationTypes
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The source code of this looks like this:
public class Neo4JApp {
private String greeting;
private GraphDatabaseService graphDb;
private Node firstNode;
private Node secondNode;
private Relationship relationship;
public static void main(final String[] args) {
Neo4JApp hello = new Neo4JApp();
hello.createDb(args[0]);
hello.removeData();
hello.shutDown();
}
void createDb(String path) {
clearDb(path);
graphDb = new EmbeddedGraphDatabase(path);
registerShutdownHook(graphDb);
Transaction tx = graphDb.beginTx();
try {
firstNode = graphDb.createNode();
firstNode.setProperty("message", "Hello, ");
secondNode = graphDb.createNode();
secondNode.setProperty("message", "World!");
relationship = firstNode.createRelationshipTo(secondNode, RelationTypes.KNOWS);
relationship.setProperty("message", "brave Neo4j ");
System.out.print(firstNode.getProperty("message"));
System.out.print(relationship.getProperty("message"));
System.out.print(secondNode.getProperty("message"));
greeting = ((String) firstNode.getProperty("message"))
+ ((String) relationship.getProperty("message"))
+ ((String) secondNode.getProperty("message"));
tx.success();
} finally {
tx.finish();
}
}
private void clearDb(String path) {
try {
FileUtils.deleteRecursively(new File(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
void removeData() {
Transaction tx = graphDb.beginTx();
try {
firstNode.getSingleRelationship(RelationTypes.KNOWS, Direction.OUTGOING).delete();
firstNode.delete();
secondNode.delete();
tx.success();
} finally {
tx.finish();
}
}
void shutDown() {
System.out.println();
System.out.println("Shutting down database ...");
graphDb.shutdown();
}
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running example before it's completed)
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
graphDb.shutdown();
}
});
}
And the used class RelationTypes looks like this:
public enum RelationTypes implements RelationshipType {
KNOWS,
WHOKNOWS,
}
The project can be found at github.
Currently i don't see the problem?...The RelationTypes are defined in the correct location...May be someone has a hint for me?
The problem was the directory of the unit test which is not allowed to be the target folder itself. It must be a separate folder under target.

Resources