Testing with GraphAware Timetree - neo4j

I've been starting to use GraphAware timetree for neo4j, and so far its working out pretty well. Now I'm trying to work out how I can unit / integration test my code that uses neo4j timetree.
I've put together some code as below... but still I'm getting the message:
org.neo4j.ogm.exception.CypherException: Error executing Cypher "Neo.ClientError.Procedure.ProcedureNotFound"; Code: Neo.ClientError.Procedure.ProcedureNotFound; Description: There is no procedure with the name `ga.timetree.events.attach` registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed.
Am I sort of on the right track?
package myproject.core;
import java.util.ArrayList;
import java.util.HashMap;
import javax.inject.Inject;
import org.junit.After;
import org.junit.runner.RunWith;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
import org.neo4j.ogm.testutil.MultiDriverTestClass;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.neo4j.template.Neo4jOperations;
import org.springframework.test.context.junit4.SpringRunner;
import com.graphaware.common.policy.NodeInclusionPolicy;
import com.graphaware.module.timetree.module.TimeTreeConfiguration;
import com.graphaware.module.timetree.module.TimeTreeModule;
import com.graphaware.runtime.GraphAwareRuntime;
import com.graphaware.runtime.GraphAwareRuntimeFactory;
import myproject.core.context.TestPersistenceContext;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = TestPersistenceContext.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AbstractTest extends MultiDriverTestClass {
#Inject
private Neo4jOperations neo4jOperations;
public AbstractTest() {
new SessionFactory("myproject.model.pojos").openSession();
TimeTreeConfiguration timeTreeConfiguration = TimeTreeConfiguration.defaultConfiguration();
TimeTreeModule timeTreeModule = new TimeTreeModule("TT.1", timeTreeConfiguration, super.getGraphDatabaseService());
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(super.getGraphDatabaseService());
runtime.registerModule(timeTreeModule);
runtime.start();
}
#After
public void clearDatabase() {
neo4jOperations.query("match (n) detach delete n;", new HashMap<>());
neo4jOperations.clear();
}
}

Please change your AbstractTest() constructor to read as follows:
public AbstractTest() {
new SessionFactory("myproject.model.pojos").openSession();
TimeTreeConfiguration timeTreeConfiguration = TimeTreeConfiguration.defaultConfiguration();
TimeTreeModule timeTreeModule = new TimeTreeModule("TT.1", timeTreeConfiguration, super.getGraphDatabaseService());
TimeTreeProcedures.register(super.getGraphDatabaseService());
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(super.getGraphDatabaseService());
runtime.registerModule(timeTreeModule);
runtime.start();
}
Note the added line: TimeTreeProcedures.register(super.getGraphDatabaseService());

Related

Failed to instantiate page(net.thucydides.core.webdriver.DriverConfigurationError: Could not instantiate class io.appium.java_client.AppiumDriver)

serenity-appium is working fine on using serenity version 1.7.4 and serenity cucumber version 1.6.3. However getting below error on using serenity and cucumber version 3.0.5 for the page
[main] WARN net.thucydides.core.pages.PageFactory - Failed to instantiate page of type class pageObjects.LoginPageMobile (net.thucydides.core.webdriver.DriverConfigurationError: Could not instantiate class io.appium.java_client.AppiumDriver)
Given User launches "Mobile" application # starter.stepdefinitions.LoginSteps.userLaunchesApplication(java.lang.String)
net.thucydides.core.pages.WrongPageError: The page object class pageObjects.LoginPageMobile could not be instantiated:
Failed to instantiate page (net.thucydides.core.webdriver.DriverConfigurationError: Could not instantiate class io.appium.java_client.AppiumDriver)
Tried with below pages
Without MobilePageObject
package pageObjects;
import io.appium.java_client.pagefactory.AndroidFindBy;
import net.serenitybdd.core.pages.PageObject;
import org.openqa.selenium.WebElement;
public class LoginPageMobile extends PageObject {
#AndroidFindBy(xpath="//android.widget.Button[#text='Log In']")
private WebElement WPLogInButton;
public void doLogin(){
typeInto(WPLogInButton,"test#test.com");
}
}
With MobilePageObject
package pageObjects;
import com.google.common.base.Predicate;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import net.serenitybdd.core.pages.PageObject;
import io.appium.java_client.android.AndroidDriver;
import net.thucydides.core.webdriver.WebDriverFacade;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class MobilePageObject extends PageObject {
public MobilePageObject(final WebDriver driver) {
super(driver, new Predicate<PageObject>() {
#Override
public boolean apply(PageObject page) {
PageFactory.initElements(new AppiumFieldDecorator(((WebDriverFacade) page.getDriver()).getProxiedDriver()), page);
return true;
}
});
}
public MobilePageObject() {
}
}
Serenity.properties
webdriver.driver= appium
appium.hub = http://localhost:4723/wd/hub
######## android CAPS ######
appium.automationName = Appium
appium.platformName= Android
appium.platformVersion = 11.0
appium.deviceName = emulator-5554
appium.app = serenity-cucumber-starter/src/test/resources/Calculator.apk
Extending PageObject rather than MobilePageObject for the page resolved the issue for serenity and cucumber version 3.0.5.

Testing a Feign Client

I've written a feign client and I would like to test that it works using a unit test.
For my case, integration tests is not the right approach for the current development stage.
The feign client is null, I receive a NullPointerException while running the test.
How can I autowire it?
Feign client
package com.myapp.clients;
import com.myapp.model.StatusResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#FeignClient(name="myClient", url="${feign.clients.my.url}")
public interface myClient {
#RequestMapping(method= RequestMethod.GET, value="/v1/users/{userId}")
StatusResponse getStatus(
#RequestHeader(value = "Auth", required = true) String authorizationHeader,
#RequestHeader(value = "my_tid", required = true) String tid,
#PathVariable("userId") String userId);
}
Tests:
package com.myapp.clients;
import com.intuit.secfraudshared.step.broker.model.StatusResponse;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class MyClientTest {
#Autowired
MyClient myClient;
#Test
public void testmyClient_status200() {
StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
Assert.assertNotNull(iusResponse);
}
}
How can autowire MyClient?
The method that has worked for me so far while trying to test Feign Clients is stubbing the response via wiremock. You would need to add dependency for wiremock.
testImplementation 'org.springframework.cloud:spring-cloud-contract-wiremock'
Then you would need to annotate as
#RunWith(SpringRunner.class)
#SpringBootTest(properties = "feign.clients.my.url=http://localhost:${wiremock.server.port}")
#AutoConfigureWireMock(port = 0)
And then stub using wiremock.
stubFor(post(urlPathMatching("/v1/users/([a-zA-Z0-9-]*)")).willReturn(aResponse().withStatus(200).withHeader("content-type", "application/json").withBody("{\"code\":200,\"status\":\"success\"})));
where ([a-zA-Z0-9-]*) is regex for {userId} assuming it is alphanumeric.
And then, of course, assert.
StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
Assert.assertNotNull(myResponse);

how to add header "UNH" to UNEdifactInterchange41 Object in smooks

I have to create an mscons export of energy values. I created a bit of code from some examples I found, but now I stuck. MSCONS needs an UNB and an UNH header.
I can add the UNB header to the UNEdifactInterchange41 object, but I don't find a method to attach the UNH header.
Here's my code so far:
import org.milyn.SmooksException;
import org.milyn.edi.unedifact.d16b.D16BInterchangeFactory;
import org.milyn.edi.unedifact.d16b.MSCONS.*;
import org.milyn.smooks.edi.unedifact.model.r41.*;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringWriter;
import org.milyn.smooks.edi.unedifact.model.r41.types.MessageIdentifier;
import org.milyn.smooks.edi.unedifact.model.r41.types.Party;
import org.milyn.smooks.edi.unedifact.model.r41.types.SyntaxIdentifier;
public class EDI {
public static void main(String[] args) throws IOException, SAXException, SmooksException {
D16BInterchangeFactory factory = D16BInterchangeFactory.getInstance();
UNEdifactInterchange41 edi = new UNEdifactInterchange41();
Mscons mscons = new Mscons();
/*UNB*/
UNB41 unb = new UNB41();
unb.setSender(null);
Party sender = new Party();
sender.setInternalId(getSenderInternalId());
sender.setCodeQualifier(getSenderCodeQualifier());
sender.setId(getSenderId());
SyntaxIdentifier si=new SyntaxIdentifier();
si.setVersionNum("3");
si.setId("UNOC");
unb.setSyntaxIdentifier(si);
unb.setSender(sender);
edi.setInterchangeHeader(unb);
/*UNH*/
UNH41 unh = new UNH41();
MessageIdentifier mi=new MessageIdentifier();
mi.setTypeSubFunctionId("MSCONS");
mi.setControllingAgencyCode("UN");
mi.setAssociationAssignedCode("2.2h");
String refno=createRefNo();
unh.setMessageIdentifier(mi);
/* How to attach UNH? */
}
}
Sounds like you got it almost right, you need to attach the UNH to message and not the opposite:
mi.setMessageIdentifier(unh);
You have an example there if you need:
https://github.com/ClaudePlos/VOrders/blob/master/src/main/java/pl/vo/integration/edifact/EdifactExportPricat.java

NoClassDefFoundError after grails package

When I run my Grails project in my local environment everything works fine however when I use grails package and deploy it to our test server it isn't able to load the page because it throws a NoClassDefFoundError
This is the code for the loading of the specific page:
package com.x.scheduledReport
import com.x.Account
import com.x.XUtil
import com.x.ResponseList
import com.x.ScheduledReport
import com.x.UserService
import com.x.scheduledReports.ScheduledReportDeleteAllCommand
import com.x.scheduledReports.ScheduledReportDeleteCommand
import com.x.scheduledReports.ScheduledReportResponse
import com.x.scheduledReports.ScheduledReportUpdateCommand
import com.x.scheduledReports.ScheduledReportsCommand
import grails.transaction.Transactional
import com.x.scheduledreport.ScheduledReportUtil
#Transactional
class ScheduledReportBusinessService {
ScheduledReportService scheduledReportService
UserService userService
def list(Map params) {
if (params.start) {
params.offset = params.start
}
if (params.length) {
params.max = Math.min(params.length ? params.length as Integer : 100, 1000)
}
params.columns = XUtil.getSearchMap(params)
Account account = userService.getAccountForCurrentUser()
def scheduledReports = scheduledReportService.findAllByAccount(params, account)
params.total = scheduledReports.count
List<ScheduledReportResponse> scheduledReportResponseList = ScheduledReportUtil.toScheduledReportResponseList(scheduledReports.list)
new ResponseList(recordsTotal: scheduledReports.count, recordsFiltered: scheduledReports.count,
data: scheduledReportResponseList, draw: params.draw ? params.draw as int : 0)
}
}
This is the error thrown in the logs
ERROR 2018-04-05 14:18:42,242
org.springframework.boot.context.web.ErrorPageFilter - Forwarding to
error page from request [/rest/scheduledreport/list/true] due to
exception [com/x/scheduledreport/ScheduledReportUtil]
java.lang.NoClassDefFoundError:
com/x/scheduledreport/ScheduledReportUtil at
com.x.scheduledReport.ScheduledReportBusinessService.$tt__list(ScheduledReportBusinessService.groovy:33)
at
com.x.scheduledReport.ScheduledReportBusinessService$_list_closure1.doCall(ScheduledReportBusinessService.groovy)
There were inconsistensies with the folder names for ScheduledReport making all the names the same fixed the issue.

Use of #Import Annotation

I have started working on Spring Security. I am doing a HelloWorld application from this link.
My question is, why do we need the #Import annotation?
While working on Spring MVC, I used to define a similar configuration file, but since it was in the same package, I did not need to import it. Why am I importing the SecurityConfig.java file here, then?
The place where I have used the #Import annotation is here
AppConfig.java:
package com.mkyong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan({ "com.mkyong.web.*" })
#Import({ SecurityConfig.class })
public class AppConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
You need to import the security into the main app config class because it won't be picked up by the #ComponentScan because the class is not within the package for scanning #ComponentScan({ "com.mkyong.web.*" }). The security config is not defined in there. You register your main class like:
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
If you don't import the security class into it then the security won't be registered in the application.

Resources