JUnit test for post Rest WS using rest-assured - post

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);
}

Related

Jena simple example java.lang.NoClassDefFoundError

I have tried this simple example and after hours spent still can not resolve the problem. I was wondering if anyone has any idea?
import org.apache.jena.rdf.model.*;
import org.apache.jena.vocabulary.*;
/** Tutorial 1 creating a simple model
*/
public class Tutorial01 extends Object {
// some definitions
static String personURI = "http://somewhere/JohnSmith";
static String fullName = "John Smith";
public static void main (String args[]) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// create the resource
Resource johnSmith = model.createResource(personURI);
// add the property
johnSmith.addProperty(VCARD.FN, fullName);
}
}
After running the program..
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/jena/rdf/model/ModelFactory
at jena.Tutorial01.main(Tutorial01.java:17)
Caused by: java.lang.ClassNotFoundException:
org.apache.jena.rdf.model.ModelFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more

OpenSessionInViewInterceptor 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]

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());
}

how to add arraylist contents to menu in jsf 2

I want to add the contents of an arraylist has meu in a jsf page but playing me anything can you help me !!!! thnks
this is the method where i fill my arraylist from database in bean
public List<String> profession_pere_list;
public String profession_pere;
//....setters & getters
public List<String> getSelectProfessions() throws SQLException, NamingException{
profession_pere_list = new ArrayList<String>();
initctx = (Context) new InitialContext();
Context envContext = (Context) initctx.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/reinscription");
cnx = ds.getConnection();
state = cnx.createStatement();
rst = state.executeQuery("select profession from professions");
while(rst.next())
{
etu = new etudiants();
prof =rst.getString(1);
etu.setProfession_pere(prof);
//profession_pere=prof;
//etu.setProfession_pere(rst.getString(1).toString());
profession_pere_list.add(prof);
}
return profession_pere_list;}
and my jsf page:
<h:selectOneMenu value="#{etudiants.profession_pere}">
<f:selectItems value="#{etudiants.profession_pere_list}"/>
so i have this error unknown source !!!
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service(Unknown Source)
cause mère
java.lang.NullPointerException
com.sun.faces.renderkit.SelectItemsIterator$GenericObjectSelectItemIterator$GenericObjectSelectItem.updateItem(Unknown Source)
com.sun.faces.renderkit.SelectItemsIterator$GenericObjectSelectItemIterator$GenericObjectSelectItem.access$600(Unknown Source)
com.sun.faces.renderkit.SelectItemsIterator$GenericObjectSelectItemIterator.getSelectItemFor(Unknown Source)
com.sun.faces.renderkit.SelectItemsIterator$IterableItemIterator.next(Unknown Source)
com.sun.faces.renderkit.SelectItemsIterator$IterableItemIterator.next(Unknown Source)
com.sun.faces.renderkit.SelectItemsIterator.next(Unknown Source)
com.sun.faces.renderkit.html_basic.MenuRenderer.renderOptions(Unknown Source)
com.sun.faces.renderkit.html_basic.MenuRenderer.renderSelect(Unknown Source)
com.sun.faces.renderkit.html_basic.MenuRenderer.encodeEnd(Unknown Source)
javax.faces.component.UIComponentBase.encodeEnd(Unknown Source)
javax.faces.component.UIComponent.encodeAll(Unknown Source)
javax.faces.component.UIComponent.encodeAll(Unknown Source)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Unknown Source)
com.sun.faces.application.view.MultiViewHandler.renderView(Unknown Source)
com.sun.faces.lifecycle.RenderResponsePhase.execute(Unknown Source)
com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
com.sun.faces.lifecycle.LifecycleImpl.render(Unknown Source)
javax.faces.webapp.FacesServlet.service(Unknown Source)
I had the same issue and the rason was a List modified concurently by different HTTP threads in ViewScoped bean:
#ViewScoped
public class Bean {
private List<Object> list;
public List<Object> getList() {
this.list = new ArrayList<>();
// code which modifies list
return this.list;
}
}
Solution - synchronize access to list:
public synchronized List<Object> getList() {
In my case I had sometimes your exception and sometimes ConcurrentModificationException.
I have also found another explanation:
http://www.adam-bien.com/roller/abien/entry/jsf_nullpointerexception_in_selectitemsiterator_java
When SelectItem label is null - you can also get your exception.

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