JpaRepository findById method returning Optional.empty when id is matching to the correct database row? - spring-boot

For some reason my PluginRepository interface doesn't want to return the object saved in my database in this test here.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PluginServiceIntegrationTest {
#Autowired
private PluginRepository pluginRepository;
#Autowired
private PluginService pluginService;
#Autowired
private PluginController pluginController;
#LocalServerPort
private int port;
private String resourceUrl;
#Before
public void setUp() {
resourceUrl = "http://localhost:" + port + "/plugin/";
}
#Test
public void notNullTest() {
assertNotNull(pluginRepository);
assertNotNull(pluginService);
assertNotNull(pluginController);
}
#Test
public void postPluginTest() {
RestTemplate restTemplate = new RestTemplate();
PluginDTO requestDto = new PluginDTO();
HttpEntity<PluginDTO> request = new HttpEntity<>(requestDto);
ResponseEntity<PluginDTO> response = restTemplate.exchange(resourceUrl + "create", HttpMethod.POST, request, PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
PluginDTO pluginDTO = response.getBody();
assertNotNull(pluginDTO);
}
#Test
public void getPluginTest() throws Exception {
PluginDTO createdDto = new PluginDTO(UUID.fromString("20a246e8-7b74-4081-bb62-6911b8ef43ef"),"Foo", "0.1", "TestAuthor");
Plugin created = new Plugin(createdDto.getUuid(), createdDto.getName(), createdDto.getVersion(), createdDto.getAuthor());
pluginRepository.saveAndFlush(created);
pluginRepository.findAll().forEach(plugin -> System.out.print(plugin.toString()));
try {
Plugin plugin = pluginRepository.findById(createdDto.getUuid());
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(pluginService.fetchPlugin(createdDto.getUuid()).toString());
assertEquals(pluginService.fetchPlugin(createdDto.getUuid()), created);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<PluginDTO> response = restTemplate.getForEntity(resourceUrl + createdDto.getUuid(), PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
}
#After
public void tearDown() {
pluginRepository.deleteAllInBatch();
}
}
System.out.println(pluginRepository.findById(createdDto.getUuid()).get().toString()); // this line
assertEquals(pluginService.fetchPlugin(createdDto.getUuid()), created);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<PluginDTO> response = restTemplate.getForEntity(resourceUrl + createdDto.getUuid(), PluginDTO.class);
assertEquals(response.getStatusCode(), HttpStatus.OK);
}
Even though the fixed values are set by the createdDto object it doesn't return it and I can see the values are in the database as well. This is what it returns...
20a246e8-7b74-4081-bb62-6911b8ef43ef:Foo:0.1:TestAuthor
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at net.ihq.plugin.controller.PluginServiceIntegrationTest.getPluginTest(PluginServiceIntegrationTest.java:79)
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.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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I am very stumped as I don't understand why it can save the object but can't get it back with the same fixed values I set it with, but it is actually there from me print the list of objects in the database on the line before the error occurs.
Repository
#Repository
public interface PluginRepository extends JpaRepository<Plugin, UUID> {
#Query(value = "SELECT * FROM plugins WHERE name=?", nativeQuery = true)
Plugin findByName(String name);
}
Entity
#Data
#Entity
#Table(name = "plugins")
#NoArgsConstructor
public class Plugin {
#Id
#Convert(converter = UUIDConverter.class)
#Column(unique = true, updatable = false, length = 36)
private UUID uuid;
private String name;
private String version;
private String author;
public Plugin(UUID uuid, String name, String version, String author) {
this.uuid = uuid;
this.name = name;
this.version = version;
if (author == null) author = "JoeTAMatthews";
this.author = author;
}
public Plugin(String name, String version, String author) {
this(UUID.randomUUID(), name, version, author);
}
public void update(PluginDTO updated) {
this.name = updated.getName();
this.version = updated.getVersion();
this.author = updated.getAuthor();
}
#Override
public String toString() {
return uuid.toString() + ":" + name + ":" + version + ":" + author;
}
}

Sorry for the inconvenience but the reason it doesn't work is because the UUID type is not supported in the database, so all I had to do was get the string type of the uuid to actually get a result because of my UUIDConverter, thanks for all your help.

Related

How to get Stringify specific column value with many braces

I am new at java spring web mvc and im currently trying to create an ajax response using spring controller.
Here is my code:
Controller Class
#Controller
#RequestMapping("/")
public class AppController {
#Autowired
EmployeeService service;
#Autowired
MessageSource messageSource;
#RequestMapping(value = { "/editAjax-{ssn}-employee" }, method = RequestMethod.GET, produces = "application/json")
public #ResponseBody Employee check1(#PathVariable String ssn,
HttpServletRequest request, HttpServletResponse response) {
Employee employee = service.findEmployeeBySsn(ssn);
return employee;
}
}
Model Class
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Size(min = 3, max = 50)
#Column(name = "NAME", nullable = false)
private String name;
#Size(min = 5, max = 200)
#Column(name = "ADDRESS", nullable = false)
private String address;
#NotNull
#Digits(integer = 8, fraction = 2)
#Column(name="SALARY", nullable = false)
private BigDecimal salary;
#NotEmpty
#Column(name="SSN", unique = true, nullable = false)
private String ssn;
#NotNull
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "JOINING_DATE", nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", address=" + address
+ ", salary=" + salary + ", ssn=" + ssn + ", joiningDate="
+ joiningDate + "]";
}
// Empty Constructor
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
}
and here is my script inside jsp
<script>
/* This function provide response from controller retrieving employee
* detail via ssn id.
*/
function searchViaAjax(obj) {
var stringResponse;
var id = obj.id;
$.ajax({
/* Controller Request Mapping */
url : "${pageContext.request.contextPath}/editAjax-${'" + id
+ "'}-employee",
type : "GET",
contentType : "application/json",
dataType : "json",
success : function(response) {
/* Convert response into String */
stringResponse = JSON.stringify(response, [ 'id', 'name',
'address', 'salary', 'ssn', 'joiningDate' ]);
console.log(stringResponse);
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
</script>
console result:
sucess! {"id":6,"name":"test","address":"Makati city","salary":124565,"ssn":"2","joiningDate":{}}
As you can see i failed to get the joiningDate value.
When i access the web url directly the output of response is this. All works fine i get the value of id,name,address,salary,ssn,joiningDate.
But in joiningDate there are so many braces and fields i think because of the type in model class that set into org.jadira.usertype.dateandtime.joda.PersistentLocalDate? How can i get only atleast the "values":[2018,3,27] in joiningDate field?
Is there a way to retrieve the values that i want only despite in many values inside joiningDate? Do i need to change the type in my model class?
{"id":6,"name":"test","address":"Makati city","salary":124565,"ssn":"2","joiningDate":{"dayOfMonth":27,"dayOfWeek":2,"era":1,"year":2018,"dayOfYear":86,"chronology":{"zone":{"fixed":true,"id":"UTC"}},"weekyear":2018,"monthOfYear":3,"yearOfEra":2018,"yearOfCentury":18,"centuryOfEra":20,"weekOfWeekyear":13,"fields":[{"lenient":false,"maximumValue":292278993,"minimumValue":-292275054,"rangeDurationField":null,"leapDurationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"durationField":{"unitMillis":31556952000,"precise":false,"name":"years","type":{"name":"years"},"supported":true},"name":"year","type":{"durationType":{"name":"years"},"rangeDurationType":null,"name":"year"},"supported":true},{"lenient":false,"maximumValue":12,"minimumValue":1,"rangeDurationField":{"unitMillis":31556952000,"precise":false,"name":"years","type":{"name":"years"},"supported":true},"leapDurationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"durationField":{"unitMillis":2629746000,"precise":false,"name":"months","type":{"name":"months"},"supported":true},"name":"monthOfYear","type":{"durationType":{"name":"months"},"rangeDurationType":{"name":"years"},"name":"monthOfYear"},"supported":true},{"maximumValue":31,"minimumValue":1,"rangeDurationField":{"unitMillis":2629746000,"precise":false,"name":"months","type":{"name":"months"},"supported":true},"lenient":false,"unitMillis":86400000,"durationField":{"unitMillis":86400000,"precise":true,"name":"days","type":{"name":"days"},"supported":true},"name":"dayOfMonth","type":{"durationType":{"name":"days"},"rangeDurationType":{"name":"months"},"name":"dayOfMonth"},"supported":true,"leapDurationField":null}],"values":[2018,3,27],"fieldTypes":[{"durationType":{"name":"years"},"rangeDurationType":null,"name":"year"},{"durationType":{"name":"months"},"rangeDurationType":{"name":"years"},"name":"monthOfYear"},{"durationType":{"name":"days"},"rangeDurationType":{"name":"months"},"name":"dayOfMonth"}]}}
UPDATE:
When i try to remove the #Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate") i got an error. it says could not deserialize.
Apr 05, 2018 12:50:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/MavenTry] threw exception [Request processing failed; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.StreamCorruptedException: invalid stream header: 32303138
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:354)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1695)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1627)
at org.hibernate.loader.Loader.getRow(Loader.java:1514)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:725)
at org.hibernate.loader.Loader.processResultSet(Loader.java:952)
at org.hibernate.loader.Loader.doQuery(Loader.java:920)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.websystique.springmvc.dao.EmployeeDaoImpl.findAllEmployee(EmployeeDaoImpl.java:44)
at com.websystique.springmvc.service.EmployeeServiceImpl.findAllEmployee(EmployeeServiceImpl.java:55)
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.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.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy112.findAllEmployee(Unknown Source)
at com.websystique.springmvc.controller.AppController.employeeList(AppController.java:61)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
For The full code reference. This is the tutorial of this program. http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/

Unit test failing for custom processor's 'optional' properties

To create a custom processor, I followed the documentation.
I made the necessary code changes in the MyProcessor.java and the MyProcessorTest runs fine except when I try to use some 'optional' properties. Note : I tried all the builder methods like required(false), addValidator() etc. for the optional properties, in vain. Actually, a validator doesn't make sense for an optional property ...
MyProcessor.java
#Tags({ "example" })
#CapabilityDescription("Provide a description")
#SeeAlso({})
#ReadsAttributes({ #ReadsAttribute(attribute = "", description = "") })
#WritesAttributes({ #WritesAttribute(attribute = "", description = "") })
#Stateful(description = "After a db-level LSN is processed, the same should be persisted as the last processed LSN", scopes = { Scope.CLUSTER })
public class MyProcessor extends AbstractProcessor {
public static final Relationship REL_SUCCESS = new Relationship.Builder()
.name("success")
.description(
"Successfully created FlowFile from SQL query result set.")
.build();
public static final Relationship REL_FAILURE = new Relationship.Builder()
.name("failure").description("SQL query execution failed. ???")
.build();
/* Start : Mandatory properties */
public static final PropertyDescriptor DBCP_SERVICE = new PropertyDescriptor.Builder()
.name("Database Connection Pooling Service")
.description(
"The Controller Service that is used to obtain connection to database")
.required(true).identifiesControllerService(DBCPService.class)
.build();
public static final PropertyDescriptor CONTAINER_DB = new PropertyDescriptor.Builder()
.name("containerDB").displayName("Container Database")
.description("The name of the container database").required(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();
...
...more mandatory properties
...
/* End : Mandatory properties */
/*Start : Optional properties */
public static final PropertyDescriptor CDC_TS_FROM = new PropertyDescriptor.Builder()
.name("cdcTSFrom").displayName("Load CDC on or after")
.description("The CDC on or after this datetime will be fetched.")
.required(false).defaultValue(null).build();
public static final PropertyDescriptor SCHEMA = new PropertyDescriptor.Builder()
.name("schema").displayName("DB Schema")
.description("The schema which contains the xxxxxx")
.defaultValue(null).required(false).build();
/*End : Optional properties */
private List<PropertyDescriptor> descriptors;
private Set<Relationship> relationships;
#Override
protected void init(final ProcessorInitializationContext context) {
final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
descriptors.add(CONTAINER_DB);
descriptors.add(DBCP_SERVICE);
...
...
...
descriptors.add(CDC_TS_FROM);
descriptors.add(SCHEMA);
...
...
...
this.descriptors = Collections.unmodifiableList(descriptors);
final Set<Relationship> relationships = new HashSet<Relationship>();
relationships.add(REL_FAILURE);
relationships.add(REL_SUCCESS);
this.relationships = Collections.unmodifiableSet(relationships);
}
#Override
public Set<Relationship> getRelationships() {
return this.relationships;
}
#Override
public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
return descriptors;
}
// TODO : Check if the component lifecycle methods esp. onScheduled() and
// onShutDown() are required
#Override
public void onTrigger(final ProcessContext context,
final ProcessSession session) throws ProcessException {
...
...
...
}
}
MyProcessorTest.java
public class MyProcessorTest {
private TestRunner testRunner;
private final String CONTAINER_DB = "test";
private final String DBCP_SERVICE = "test_dbcp";
...
...
...
private final String SCHEMA = "dbo";
private final String CDC_TS_FROM = "";
...
...
...
#Before
public void init() throws InitializationException {
testRunner = TestRunners.newTestRunner(MyProcessor.class);
final DBCPService dbcp = new DBCPServiceSQLServerImpl(...);
final Map<String, String> dbcpProperties = new HashMap<>();
testRunner = TestRunners.newTestRunner(MyProcessor.class);
testRunner.addControllerService(DBCP_SERVICE, dbcp, dbcpProperties);
testRunner.enableControllerService(dbcp);
testRunner.assertValid(dbcp);
testRunner.setProperty(MyProcessor.DBCP_SERVICE, DBCP_SERVICE);
testRunner.setProperty(MyProcessor.CONTAINER_DB, CONTAINER_DB);
...
...
...
testRunner.setProperty(MyProcessor.CDC_TS_FROM, CDC_TS_FROM);
testRunner.setProperty(MyProcessor.SCHEMA, SCHEMA);
...
...
...
}
#Test
public void testProcessor() {
testRunner.run();
}
/**
* Simple implementation only for MyProcessor processor testing.
*/
private class DBCPServiceSQLServerImpl extends AbstractControllerService
implements DBCPService {
private static final String SQL_SERVER_CONNECT_URL = "jdbc:sqlserver://%s;database=%s";
private String containerDB;
private String password;
private String userName;
private String dbHost;
public DBCPServiceSQLServerImpl(String containerDB, String password,
String userName, String dbHost) {
super();
this.containerDB = containerDB;
this.password = password;
this.userName = userName;
this.dbHost = dbHost;
}
#Override
public String getIdentifier() {
return DBCP_SERVICE;
}
#Override
public Connection getConnection() throws ProcessException {
try {
Connection connection = DriverManager.getConnection(String
.format(SQL_SERVER_CONNECT_URL, dbHost, containerDB),
userName, password);
return connection;
} catch (final Exception e) {
throw new ProcessException("getConnection failed: " + e);
}
}
}
}
Now if I comment the optional properties in the test class :
//testRunner.setProperty(MyProcessor.CDC_TS_FROM, CDC_TS_FROM);
//testRunner.setProperty(MyProcessor.SCHEMA, SCHEMA);
, the test completes normally but if I enable any or all of the optional properties, say, CDC_TS_FROM, then I the test case assertion fails, no matter what value I put for CDC_TS_FROM :
java.lang.AssertionError: Processor has 1 validation failures:
'cdcTSFrom' validated against '' is invalid because 'cdcTSFrom' is not a supported property
at org.junit.Assert.fail(Assert.java:88)
at org.apache.nifi.util.MockProcessContext.assertValid(MockProcessContext.java:251)
at org.apache.nifi.util.StandardProcessorTestRunner.run(StandardProcessorTestRunner.java:161)
at org.apache.nifi.util.StandardProcessorTestRunner.run(StandardProcessorTestRunner.java:152)
at org.apache.nifi.util.StandardProcessorTestRunner.run(StandardProcessorTestRunner.java:147)
at org.apache.nifi.util.StandardProcessorTestRunner.run(StandardProcessorTestRunner.java:142)
at org.apache.nifi.util.StandardProcessorTestRunner.run(StandardProcessorTestRunner.java:137)
at processors.NiFiCDCPoC.sqlserver.MyProcessorTest.testProcessor(MyProcessorTest.java:74)
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:497)
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.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Edit-1 :
I added two(?) validators :
public static final PropertyDescriptor CDC_TS_FROM = new PropertyDescriptor.Builder()
.name("cdcTSFrom").displayName("Load CDC on or after")
.description("The CDC on or after this datetime will be fetched.")
.required(false).defaultValue(null).addValidator(Validator.VALID)
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR).build();
Error :
java.lang.AssertionError: Processor has 1 validation failures:
'cdcTSFrom' validated against '2017-03-06 10:00:00' is invalid because Must be of format <duration> <TimeUnit> where <duration> is a non-negative integer and TimeUnit is a supported Time Unit, such as: nanos, millis, secs, mins, hrs, days
All Property Descriptors (required or optional) must have a Validator set explicitly, otherwise it will return the error you are seeing. It appears you are not looking to perform validation, but you still must set a validator, so on your optional properties add the following to the builder:
.addValidator(Validator.VALID)
EDIT (see comments below): Marking the PropertyDescriptor as required(false) allows it to be an optional property and thus can have no value specified. If the user enters a value, and you want to validate that against certain rules, you can add that particular Validator (or write your own and add that). For a Time Period (2 seconds, e.g.), and for other cases, there are a set of built-in validators, for example allowing only values between 2 and 20 seconds:
.addValidator(StandardValidators.createTimePeriodValidator(
2, TimeUnit.SECONDS, 20, TimeUnit.SECONDS
))

How to resolve this error TransactionException: commit failed?

i have a Post request ajax like this :
$.ajax({
"url":serverPath+"/taxiws/clients",
"type": "POST",
contentType: "application/json",
dataType: "text",
"data": JSON.stringify(obj),
"success": function(data) {
console.log("success!!!");
$("#LoadingBackgroundPopup").hide();
window.location.href="reservationclient.html";
},"error": function(error) {
console.log(error);
}
});
method Post in web service:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json, UriComponentsBuilder uriBuilder) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
System.out.println("hello post");
try {
Client client = Client.fromJsonToClient(json);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(client.getPassword());
client.setPassword(hashedPassword);
System.out.println("Passowrd hashé "+hashedPassword);
client.persist();
RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
headers.add("Location",uriBuilder.path(a.value()[0]+"/"+client.getIdclient().toString()).build().toUriString());
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
but when i excute this requet i found this problem :
!JavaScript LOG: {"ERROR":org.hibernate.TransactionException: commit failed; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: commit failed"}
i added this command line e.getStackTrace(); in my web service ,i found this issue:
2016-04-14 11:56:57,043 [http-bio-8080-exec-5] ERROR org.springframework.transaction.aspectj.AnnotationTransactionAspect - Application exception overridden by rollback exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321)
at org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect.ajc$afterThrowing$org_springframework_orm_jpa_aspectj_JpaExceptionTranslatorAspect$1$18a1ac9(JpaExceptionTranslatorAspect.aj:33)
at com.binov.webservice.web.Client.persist_aroundBody26(Client.java:243)
at com.binov.webservice.web.Client$AjcClosure27.run(Client.java:1)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:59)
at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:65)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:63)
at com.binov.webservice.web.Client.persist(Client.java:241)
at com.binov.webservice.ClientController.createFromJson(ClientController.java:69)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.filters.CorsFilter.handleSimpleCORS(CorsFilter.java:302)
at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:170)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
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.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy36.persist(Unknown Source)
... 57 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 63 more
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "idclient" violates not-null constraint
Détail : Failing row contains (null, 04-04-2016, dd#mail.com, dd, $2a$10$FXBRGcoZ3uFAD649LDgfMucLXveFDAF1NyrlCvdY6gjpUgpa/gfkO, dd, client, 1234567890, dd).
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 84 more
my classe client.java
package com.binov.webservice.web;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;
import java.util.Collection;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
#Entity
#Table(schema = "public",name = "client")
#Configurable
public class Client {
#Column(name = "datenaissance", length = 255)
private String datenaissance;
#Column(name = "email", length = 255)
private String email;
#Column(name = "nom", length = 255)
private String nom;
#Column(name = "password", length = 255)
private String password;
#Column(name = "prenom", length = 255)
private String prenom;
#Column(name = "role", length = 255)
private String role;
#Column(name = "telephone", length = 255)
private String telephone;
#Column(name = "username", length = 255)
private String username;
public String getDatenaissance() {
return datenaissance;
}
public void setDatenaissance(String datenaissance) {
this.datenaissance = datenaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idclient")
private Integer idclient;
public Integer getIdclient() {
return this.idclient;
}
public void setIdclient(Integer id) {
this.idclient = id;
}
#PersistenceContext
transient EntityManager entityManager;
public static final List<String> fieldNames4OrderClauseFilter = java.util.Arrays.asList("");
public static final EntityManager entityManager() {
EntityManager em = new Client().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public String toJson() {
return new JSONSerializer()
.exclude("*.class").serialize(this);
}
public String toJson(String[] fields) {
return new JSONSerializer()
.include(fields).exclude("*.class").serialize(this);
}
public static Client fromJsonToClient(String json) {
return new JSONDeserializer<Client>()
.use(null, Client.class).deserialize(json);
}
public static String toJsonArray(Collection<Client> collection) {
return new JSONSerializer()
.exclude("*.class").serialize(collection);
}
public static String toJsonArray(Collection<Client> collection, String[] fields) {
return new JSONSerializer()
.include(fields).exclude("*.class").serialize(collection);
}
public static Collection<Client> fromJsonArrayToClients(String json) {
return new JSONDeserializer<List<Client>>()
.use("values", Client.class).deserialize(json);
}
public static long countClients() {
return entityManager().createQuery("SELECT COUNT(o) FROM Client o", Long.class).getSingleResult();
}
public static List<Client> findAllClients() {
return entityManager().createQuery("SELECT o FROM Client o", Client.class).getResultList();
}
public static List<Client> findAllClients(String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Client o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Client.class).getResultList();
}
// find a client with her username and password
// public static List<Client> findClientByUsernamePassword(String username,String password)
// {
// // TODO Auto-generated method stub
// if((username==null) && (password==null))return null;
// return entityManager().createQuery("SELECT o FROM Client o where o.username=:username and o.password=:password", Client.class).setParameter("username", username).setParameter("password", password).getSingleResult();
// }
//find a cient by username
public static List<Client> findClientByUsernamePassword(String username)
{
// TODO Auto-generated method stub
if((username==null))return null;
return (List<Client>) entityManager().createQuery("SELECT o FROM Client o WHERE o.username=:username",Client.class).setParameter("username", username).getResultList();
}
public static List<Client> findClientByUsernamePassword(String username2,String password2) {
// TODO Auto-generated method stub
return entityManager().createQuery("SELECT o FROM Client o where o.username=:username and o.password=:password", Client.class).setParameter("username", username2).setParameter("password", password2).getResultList();
}
public static Client findClient(Integer idclient) {
if (idclient == null) return null;
return entityManager().find(Client.class, idclient);
}
public static List<Client> findClientEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Client o", Client.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
public static List<Client> findClientEntries(int firstResult, int maxResults, String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Client o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Client.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
#Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
#Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Client attached = Client.findClient(this.idclient);
this.entityManager.remove(attached);
}
}
#Transactional
public void flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
#Transactional
public void clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
#Transactional
public Client merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Client merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
public String toString() {
return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames("Client").toString();
}
}
please ,How can I fix this issue?

NotInTransactionException when adding to mapped set

I have two #NodeEntities mapped via SDN using simple mapping, PersonNode and FamilyNode. FamilyNode has a #RelatedTo collection, children. I also have a FamilyService (using Spring's #Service annotation) with #Transactional annotation on an updateFamily method. This method loads the FamilyNode given an id, and uses a callback interface to modify the node. In one implementation of the callback, I am adding a PersonNode to the children collection, and this is generating the NotInTransactionException, specifically at the point that Neo4J is attempting to create the relationship between the FamilyNode and the PersonNode.
Source code can be found at github and in particular a failing test. Here are relevant bits of the code:
FamilyNode.java:
#NodeEntity
public class FamilyNode implements Family {
#Indexed(indexName = "families", unique = true)
private String id;
#GraphId
private Long identifier;
#RelatedTo(elementClass = PersonNode.class, type = "CHILD")
private Set<Person> children;
void addChild(Person child) {
if (this.children == null) {
this.children = new HashSet<>();
}
this.children.add(child);
}
}
PersonNode.java:
#NodeEntity
public class PersonNode implements Person {
#RelatedTo(elementClass = FamilyNode.class, type = "CHILD", direction = INCOMING)
private Family childOf;
#Indexed(indexName = "people", unique = true)
private String id;
#GraphId
private Long identifier;
}
FamilyRepository.java:
public interface FamilyRepository extends GraphRepository<Family> {
public FamilyNode findById(String id);
}
FamilyServiceImpl.java:
#Service
public class FamilyServiceImpl implements FamilyService {
#Autowired
private FamilyRepository families;
#Autowired
private Neo4jTemplate template;
#Override
public List<Family> getFamilies(String[] ids) {
List<Family> families = new ArrayList<>();
for (String id : ids) {
families.add(getFamily(id));
}
return families;
}
#Override
public Family getFamily(String id) {
return familyNode(id);
}
#Override
#Transactional
public Family createFamily(Family family) {
return lazyLoadRelationships((FamilyNode) this.families.save(family));
}
#Override
#Transactional
public Family updateFamily(String id, FamilyNodeUpdater updater) {
return this.families.save(updater.update(familyNode(id)));
}
private FamilyNode familyNode(String id) {
return lazyLoadRelationships(this.families.findById(id));
}
private FamilyNode lazyLoadRelationships(FamilyNode family) {
this.template.fetch(family.getFather());
this.template.fetch(family.getMother());
this.template.fetch(family.getChildren());
return family;
}
}
and the failing test, FamilyServiceTest.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { TestConfig.class })
public class FamilyServiceTest {
#Configuration
#ComponentScan(basePackageClasses = { com.bonevich.ancestral.family.FamilyServiceImpl.class }, resourcePattern = "FamilyServiceImpl.class")
#EnableNeo4jRepositories(basePackageClasses = { com.bonevich.ancestral.family.FamilyNode.class })
static class TestConfig extends Neo4jConfiguration {
#Bean
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder("/data/neo4j/ancestral-familyservicetest/")
.newGraphDatabase();
}
}
#Autowired
private FamilyService families;
#Autowired
private GraphDatabaseService graphDatabaseService;
#Autowired
private Neo4jTemplate neo4jTemplate;
#Test
public void testUpdateFamily() {
this.families.createFamily(FamilyNode.instance("testFamily"));
Transaction tx = this.graphDatabaseService.beginTx();
PersonNode person = PersonNode.instance("John", "Johanson", "M", "a_person");
PersonNode expectedChild = this.neo4jTemplate.save(person);
final long childId = expectedChild.getIdentifier();
tx.success();
tx.finish();
Family actualFamily = this.families.updateFamily("testFamily", new FamilyNodeUpdater() {
#Override
public FamilyNode update(FamilyNode family) {
family.addChild(FamilyServiceTest.this.neo4jTemplate.findOne(childId, PersonNode.class));
return family;
}
});
assertThat(actualFamily.getId(), is("testFamily"));
assertThat(actualFamily.getChildren().get(0), is((Person) expectedChild));
}
}
Running this test yields the following exception stack:
org.neo4j.graphdb.NotInTransactionException
at org.neo4j.kernel.impl.core.NoTransactionState.acquireWriteLock(NoTransactionState.java:43)
at org.neo4j.kernel.impl.transaction.LockType$2.acquire(LockType.java:51)
at org.neo4j.kernel.impl.core.NodeManager.getNodeForProxy(NodeManager.java:473)
at org.neo4j.kernel.InternalAbstractGraphDatabase$6.lookup(InternalAbstractGraphDatabase.java:733)
at org.neo4j.kernel.impl.core.NodeProxy.createRelationshipTo(NodeProxy.java:207)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.obtainSingleRelationship(RelationshipHelper.java:62)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.createSingleRelationship(RelationshipHelper.java:142)
at org.springframework.data.neo4j.fieldaccess.RelationshipHelper.createAddedRelationships(RelationshipHelper.java:96)
at org.springframework.data.neo4j.fieldaccess.RelatedToFieldAccessor.createAddedRelationships(RelatedToFieldAccessor.java:78)
at org.springframework.data.neo4j.fieldaccess.RelatedToCollectionFieldAccessorFactory$RelatedToCollectionFieldAccessor.setValue(RelatedToCollectionFieldAccessorFactory.java:68)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.updateValue(ManagedFieldAccessorSet.java:112)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.update(ManagedFieldAccessorSet.java:100)
at org.springframework.data.neo4j.fieldaccess.ManagedFieldAccessorSet.add(ManagedFieldAccessorSet.java:126)
at com.bonevich.ancestral.family.FamilyNode.addChild(FamilyNode.java:124)
at com.bonevich.ancestral.family.FamilyServiceTest$1.update(FamilyServiceTest.java:64)
at com.bonevich.ancestral.family.FamilyServiceImpl.updateFamily(FamilyServiceImpl.java:42)
at com.bonevich.ancestral.family.FamilyServiceTest.testUpdateFamily(FamilyServiceTest.java:61)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I have got to believe I am missing something in configuring SDN or Transactions, but have been unable to track it down.
I recently answered this question here:
Spring Data Neo4J - NotInTransactionException while modifying set of nodeEntity
In short, it has to do with the fact that these List are special list which are backed by SDN and any modification is immediately persisted to the DB. If you want to prevent this behaviour, you should use Iterable in your model classes. If you have some more question after reading the link, just post them as a comment.

Spring REST Controller Test with spring-test-mvc framework

This question is next to the question I had asked here. I am using spring-test-mvc framework to test REST controller. Please see the above link to see my code for the REST Controller I have.
My test for GET is working fine but I can't do a POST. I get an exception when I try do so. This is my first time testing a REST controller.
Here's my PcUserControllerTest class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:/applicationContextTest.xml")
public class PcUserControllerTest {
#Autowired
PcUserService pcUserService;
#Autowired
PcUserController pcUserController;
PcUser pcUser;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
mockMvc = standaloneSetup(pcUserController).build();
pcUser = new PcUser("John", "Li", "Weasley", "john", "john");
pcUserService.create(pcUser);
}
#After
public void tearDown() throws Exception {
pcUserService.delete(pcUser.getId());
}
#Test
public void shouldGetPcUser() throws Exception {
this.mockMvc.perform(get("/pcusers/" + pcUser.getId()).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
#Test
public void shouldCreatePcUser() throws Exception {
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
this.mockMvc.perform(post("/pcusers/create/" + newUser).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
}
Exception I get when I execute shouldCreatePcUser:
java.lang.IllegalArgumentException: Not enough variable values available to expand ["firstName"]
at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:1011)
at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:443)
at org.springframework.web.util.UriComponents.access$1(UriComponents.java:431)
at org.springframework.web.util.UriComponents$FullPathComponent.expand(UriComponents.java:790)
at org.springframework.web.util.UriComponents.expandInternal(UriComponents.java:413)
at org.springframework.web.util.UriComponents.expand(UriComponents.java:404)
at org.springframework.web.util.UriTemplate.expand(UriTemplate.java:121)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.expandUrl(MockMvcRequestBuilders.java:51)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.request(MockMvcRequestBuilders.java:45)
at org.springframework.test.web.server.request.MockMvcRequestBuilders.post(MockMvcRequestBuilders.java:28)
at com.project.cleaner.controller.test.PcUserControllerTest.shouldCreatePcUser(PcUserControllerTest.java:69)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
My PcUser looks like
#Document
public class PcUser extends BaseEntity {
private String firstName;
private String middleName;
private String lastName;
private String username;
private String password;
public PcUser() {
super();
}
public PcUser(String firstName, String middleName, String lastName,
String username, String password) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.username = username;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
// JSONObject jsonPcUser = new JSONObject();
// jsonPcUser.put("id", this.getId());
// jsonPcUser.put("firstName", this.firstName);
// jsonPcUser.put("middleName", this.middleName);
// jsonPcUser.put("lastName", this.lastName);
// jsonPcUser.put("username", this.username);
//
// return jsonPcUser.toJSONString();
return "{\"firstName\":" + this.firstName + ", "
+ "\"middleName\":" + this.middleName + ", "
+ "\"lastName\":" + this.lastName + ", "
+ "\"username\":" + this.username
+ "}";
}
}
BaseEntity:
public class BaseEntity {
#Id
private String id;
public BaseEntity() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I don't understand this exception. If anyone could guide me in the right direction would be really appreciated.
It seems, as beerbajay mentions, that the problem is that what you are trying to post to your controller is a PcUser as a URL/path parameter instead of in the actual body of the HTTP request.
I am using the org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#content(String) method to set the body of the HTTP request itself (as opposed to substitute parts of the URL or add URL parameters) like this:
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
this.mockMvc.perform(post("/pcusers/create/")
.content(newUser.toString()) // <-- sets the request content !
.accept(MediaType.APPLICATION_JSON)
.andExpect(status().isOk());
Okay, you have this as your get:
get("/pcusers/" + pcUser.getId())
Which makes sense, because you want to get the resource at /pcusers/123/, but then you have:
PcUser newUser = new PcUser("Mike", "Li", "Donald", "mike", "mike");
post("/pcusers/create/" + newUser)
Which doesn't really make sense since you'll be performing a toString() on the newUser object, then concatenating that with the /pcusers/create/ string. So you're probably doing a request to something like /pcusers/create/com.mycompany.PcUser#1596138, which is probably not what you want.

Resources