I am trying a very basic example of Spring Data Redis, where I want to store a User object in Redis and then return it:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Builder
class BasicUser {
private String name;
private String surname;
private String emailAddress;
private Integer age;
}
#Test
public void storeUserInRedisWithRedisTemplateTest() {
BasicUser user = BasicUser
.builder()
.age(22)
.name("testuser")
.surname("testsurname")
.emailAddress("address#address.com")
.build();
redisTemplate.opsForValue().set("userWithTemplate", user, 10800);
BasicUser returnedUser = (BasicUser) redisTemplate.opsForValue().get("userWithTemplate");
assertThat(returnedUser.emailAddress, is(user.emailAddress));
}
The error is:
org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803); nested exception is java.io.CharConversionException: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:152)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:130)
at org.springframework.data.redis.core.AbstractOperations.deserializeValue(AbstractOperations.java:335)
at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:61)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:228)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:188)
at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:96)
at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:53)
at com.kuluvalley.guru.server.service.UserSessionCacheServiceTest.storeUserInRedisWithRedisTemplateTest(UserSessionCacheServiceTest.java:123)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.io.CharConversionException: Invalid UTF-32 character 0x7b214063 (above 0x0010ffff) at char #2700, byte #10803)
at com.fasterxml.jackson.core.io.UTF32Reader.reportInvalid(UTF32Reader.java:195)
at com.fasterxml.jackson.core.io.UTF32Reader.read(UTF32Reader.java:158)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._loadMore(ReaderBasedJsonParser.java:250)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipWSOrEnd(ReaderBasedJsonParser.java:2354)
at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:672)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4340)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4189)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3266)
at org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer.deserialize(GenericJackson2JsonRedisSerializer.java:150)
... 40 more
In Redis, the value looks like:
[MANY MORE 0x00]
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00{\"#class\":\"com.org.BasicUser\",\"name\":\"testuser\",\"surname\":\"testsurname\",\"emailAddress\":\"address#address.com\",\"age\":22}"
The relevant Redis Configuration is as follows:
#Configuration
public class RedisConfig {
#Bean
public RedisConnectionFactory redisConnectionFactory(Environment env) {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(env.getRequiredProperty("redis.hostname"));
configuration.setPort(env.getProperty("redis.port", Integer.class, 6379));
return new LettuceConnectionFactory(configuration);
}
#Bean
public StringRedisTemplate redisTemplate(Environment env) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory(env));
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
I would expect this to just work as I am reading and writing the same data. Also the amount 0x00 is worrying. Is it best practice using Strings as values? What am I missing?
Basically, because you are using the wrong api not expected:
void set(K key, V value, long offset);
You should use:
void set(K key, V value, long timeout, TimeUnit unit);
with code:
redisTemplate.opsForValue().set("userWithTemplate", user, 10800, TimeUnit.SECONDS);
Related
We switched from 2.4.0 to 2.7.0. What might cause this? I can't rule out a problem in our code but we are not in the stack.
22:39:36.270 [mgmt-#66] ERROR o.a.i.i.p.task.GridTaskWorker - Failed
to obtain remote job result policy for result from
ComputeTask.result(..) method (will fail the whole task):
GridJobResultImpl [job=C2 [c=LoadCacheJobV2 [keepBinary=false]],
sib=GridJobSiblingImpl
[sesId=6461c7cd961-d4d7605d-33c7-4941-84bc-f6eca074593f,
jobId=7461c7cd961-d4d7605d-33c7-4941-84bc-f6eca074593f,
nodeId=503c524c-c53a-4f98-aadd-4c95ac2b168b, isJobDone=false],
jobCtx=GridJobContextImpl
[jobId=7461c7cd961-d4d7605d-33c7-4941-84bc-f6eca074593f,
timeoutObj=null, attrs={}], node=TcpDiscoveryNode
[id=503c524c-c53a-4f98-aadd-4c95ac2b168b, addrs=[127.0.0.1,
172.17.0.2], sockAddrs=[/127.0.0.1:47500, /
172.17.0.2:47500], discPort=47500, order=1, intOrder=1, lastExchangeTime=1554182314332, loc=false,
ver=2.4.0#20180305-sha1:aa342270, isClient=false], ex=class
o.a.i.IgniteException: null, hasRes=true, isCancelled=false,
isOccupied=true] org.apache.ignite.IgniteException: Remote job threw
user exception (override or implement ComputeTask.result(..) method if
you would like to have automatic failover for this exception).
at org.apache.ignite.compute.ComputeTaskAdapter.result(ComputeTaskAdapter.java:101)
at org.apache.ignite.internal.processors.task.GridTaskWorker$5.apply(GridTaskWorker.java:1047)
at org.apache.ignite.internal.processors.task.GridTaskWorker$5.apply(GridTaskWorker.java:1040)
at org.apache.ignite.internal.util.IgniteUtils.wrapThreadLoader(IgniteUtils.java:6655)
at org.apache.ignite.internal.processors.task.GridTaskWorker.result(GridTaskWorker.java:1040)
at org.apache.ignite.internal.processors.task.GridTaskWorker.onResponse(GridTaskWorker.java:858)
at org.apache.ignite.internal.processors.task.GridTaskProcessor.processJobExecuteResponse(GridTaskProcessor.java:1077)
at org.apache.ignite.internal.processors.task.GridTaskProcessor$JobMessageListener.onMessage(GridTaskProcessor.java:1312)
at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1555)
at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:1183)
at org.apache.ignite.internal.managers.communication.GridIoManager.access$4200(GridIoManager.java:126)
at org.apache.ignite.internal.managers.communication.GridIoManager$9.run(GridIoManager.java:1090)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.ignite.IgniteException: null
at org.apache.ignite.internal.processors.closure.GridClosureProcessor$C2.execute(GridClosureProcessor.java:1858)
at org.apache.ignite.internal.processors.job.GridJobWorker$2.call(GridJobWorker.java:566)
at org.apache.ignite.internal.util.IgniteUtils.wrapThreadLoader(IgniteUtils.java:6623)
at org.apache.ignite.internal.processors.job.GridJobWorker.execute0(GridJobWorker.java:560)
at org.apache.ignite.internal.processors.job.GridJobWorker.body(GridJobWorker.java:489)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110)
at org.apache.ignite.internal.processors.job.GridJobProcessor.processJobExecuteRequest(GridJobProcessor.java:1123)
at org.apache.ignite.internal.processors.job.GridJobProcessor$JobExecutionListener.onMessage(GridJobProcessor.java:1921)
... 7 common frames omitted
Caused by: org.apache.ignite.IgniteException: null
at org.apache.ignite.internal.util.IgniteUtils.convertException(IgniteUtils.java:980)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJob.localExecute(GridCacheAdapter.java:5525)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJobV2.localExecute(GridCacheAdapter.java:5569)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$TopologyVersionAwareJob.execute(GridCacheAdapter.java:6184)
at org.apache.ignite.compute.ComputeJobAdapter.call(ComputeJobAdapter.java:132)
at org.apache.ignite.internal.processors.closure.GridClosureProcessor$C2.execute(GridClosureProcessor.java:1855)
... 14 common frames omitted
Caused by: org.apache.ignite.IgniteCheckedException: null
at org.apache.ignite.internal.util.IgniteUtils.cast(IgniteUtils.java:7244)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.sessionEnd0(GridCacheStoreManagerAdapter.java:943)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.loadCache(GridCacheStoreManagerAdapter.java:549)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheAdapter.localLoadCache(GridDhtCacheAdapter.java:608)
at org.apache.ignite.internal.processors.cache.GridCacheProxyImpl.localLoadCache(GridCacheProxyImpl.java:217)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJob.localExecute(GridCacheAdapter.java:5520)
...18 common frames omitted Caused by: java.lang.NullPointerException: null
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter$SessionData.access$900(GridCacheStoreManagerAdapter.java:964)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.sessionEnd0(GridCacheStoreManagerAdapter.java:937)
...22 common frames omitted
22:39:36.293 [pool-3-thread-1]
ERROR c.b.a.c.c.i.cache.CeresCacheManager - There was an issue in loading data for cache ceres-daily-2019-02-27. Issue: ()
java.lang.NullPointerException: null
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter$SessionData.access$900(GridCacheStoreManagerAdapter.java:964)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.sessionEnd0(GridCacheStoreManagerAdapter.java:937)
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.loadCache(GridCacheStoreManagerAdapter.java:549)
at org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheAdapter.localLoadCache(GridDhtCacheAdapter.java:608)
at org.apache.ignite.internal.processors.cache.GridCacheProxyImpl.localLoadCache(GridCacheProxyImpl.java:217)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJob.localExecute(GridCacheAdapter.java:5520)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJobV2.localExecute(GridCacheAdapter.java:5569)
at org.apache.ignite.internal.processors.cache.GridCacheAdapter$TopologyVersionAwareJob.execute(GridCacheAdapter.java:6184)
at org.apache.ignite.compute.ComputeJobAdapter.call(ComputeJobAdapter.java:132)
at org.apache.ignite.internal.processors.closure.GridClosureProcessor$C2.execute(GridClosureProcessor.java:1855)
at org.apache.ignite.internal.processors.job.GridJobWorker$2.call(GridJobWorker.java:566)
at org.apache.ignite.internal.util.IgniteUtils.wrapThreadLoader(IgniteUtils.java:6623)
at org.apache.ignite.internal.processors.job.GridJobWorker.execute0(GridJobWorker.java:560)
at org.apache.ignite.internal.processors.job.GridJobWorker.body(GridJobWorker.java:489)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110)
at org.apache.ignite.internal.processors.job.GridJobProcessor.processJobExecuteRequest(GridJobProcessor.java:1123)
at org.apache.ignite.internal.processors.job.GridJobProcessor$JobExecutionListener.onMessage(GridJobProcessor.java:1921)
at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1555)
at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:1183)
at org.apache.ignite.internal.managers.communication.GridIoManager.access$4200(GridIoManager.java:126)
at org.apache.ignite.internal.managers.communication.GridIoManager$9.run(GridIoManager.java:1090)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
public class XYZLoader
extends CacheLoadOnlyStoreAdapter<XYZKey, byte[], XYZRecord>
implements ComputeJob, Serializable {
public XYZLoader(...) {
reconfigureCacheLoadOnlyStoreAdapter(gridNodePhysicalThreadCount, externalParallelism);
}
private void reconfigureCacheLoadOnlyStoreAdapter(int gridNodePhysicalThreadCount, int externalParallelism) {
int physicalThreadCount = ...
this.setBatchSize(...);
this.setBatchQueueSize(...);
this.setThreadsCount(...);
}
int[] getLocalPartitions(Ignite ignite) {
//...
return ...;
}
#Override
protected Iterator<XYZRecord> inputIterator(#Nullable Object... args) throws CacheLoaderException {
int[] parts = getLocalPartitions(ignite);
IgniteCluster cluster = ignite.cluster();
ClusterNode localNode = cluster.localNode();
int partitionCount = ignite.affinity(dataloadDescriptor.cacheName).partitions();
Iterator<XYZRecord> reader = new XYZReader(parts, ...);
iteratorFinishedFlag = false;
return new Iterator<XYZRecord>() {
// wrap inner iterator reader here..
};
}
protected IgniteBiTuple<XYZKey, byte[]> parse(XYZRecord rec, #Nullable Object... args) {
// parsing foo...
return record;
}
#IgniteInstanceResource
public void setIgnite(Ignite ignite) {
this.ignite = ignite;
}
#Override // ComputeJob
public void cancel() {
throw new RuntimeException("Not implemented");
}
#Override // ComputeJob
public Object execute() throws IgniteException {
throw new RuntimeException("Not implemented");
}
#TaskSessionResource
public void setTaskSession(ComputeTaskSession taskSes) {
ComputeTaskSession ses = taskSes;
logger.info(... ses);
}
}
My bet that you forgot to call super.method() somewhere in your CacheStore implementation, leading to partial initialization of underlying data structures. In loadCache() or loadFromStore() perhaps.
I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
Technologies used:
Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8
I have this classes
public class DeviceEvent {
public DeviceEvent(Device device) {
this.device = device;
}
private Device device;
private Long id;
private Double latitude;
private Double longitude;
private Date dateReceived;
private String message;
private Float rssi;
private Integer battery;
private Boolean alarm;
private Boolean processed;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Date getDateReceived() {
return dateReceived;
}
public void setDateReceived(Date dateReceived) {
this.dateReceived = dateReceived;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Float getRssi() {
return rssi;
}
public void setRssi(Float rssi) {
this.rssi = rssi;
}
public Integer getBattery() {
return battery;
}
public void setBattery(Integer battery) {
this.battery = battery;
}
public Boolean getAlarm() {
return alarm;
}
public void setAlarm(Boolean alarm) {
this.alarm = alarm;
}
public Boolean getProcessed() {
return processed;
}
public void setProcessed(Boolean processed) {
this.processed = processed;
}
}
but I got this error executing this test:
Device device = new Device("C380F");
DeviceEvent deviceEvent = new DeviceEvent(device);
deviceEvent.setId(Sequencer.getNextVal());
deviceEvent.setAlarm(Boolean.FALSE);
deviceEvent.setBattery(78);
deviceEvent.setDateReceived(new Date());
deviceEvent.setLatitude(50.834015);
deviceEvent.setLongitude(4.377885);
deviceEvent.setMessage("FAKE_MSG");
deviceEvent.setProcessed(Boolean.FALSE);
deviceEvent.setRssi((float)80);
repository.insert(deviceEvent);
...
#Override
public long insert(DeviceEvent newDeviceEvent) {
long id = Sequencer.getNextVal();
int numOfRowsAffected = jdbcTemplate.update(
"insert into T_DEVICE_EVENT (ID, DEVICE_ID, LATITUDE, LONGITUDE, MESSAGE, DATE_RECEIVED, RSSI, BATTERY, ALARM, PROCESSED) " +
" values (?,?,?,?,?,?,?,?,?,?);",
id,
newDeviceEvent.getDevice().getId(),
newDeviceEvent.getLatitude(),
newDeviceEvent.getLongitude(),
newDeviceEvent.getMessage(),
newDeviceEvent.getRssi(),
newDeviceEvent.getBattery(),
newDeviceEvent.getAlarm(),
0);
if (numOfRowsAffected==1) return id;
else return -1;
}
..
the table
CREATE TABLE IF NOT EXISTS t_device_event (
id bigint PRIMARY KEY,
device_id bigint NOT NULL,
latitude decimal NULL,
longitude decimal NULL,
message varchar(100) ,
date_received timestamp,
rssi float,
battery int,
alarm boolean,
processed boolean,
FOREIGN KEY (device_id) REFERENCES public.t_device(id));
the error:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into T_DEVICE_EVENT (ID, DEVICE_ID, LATITUDE, LONGITUDE, MESSAGE, DATE_RECEIVED, RSSI, BATTERY, ALARM, PROCESSED) values (?,?,?,?,?,?,?,?,?,?);]; nested exception is java.sql.SQLSyntaxErrorException: incompatible data type in conversion
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:91)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:931)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:941)
at com.ideefecloud.iot.repository.JdbcDeviceEventRepository.insert(JdbcDeviceEventRepository.java:44)
at com.ideefecloud.iot.repository.JdbcDeviceEventRepositoryTests.testInsert(JdbcDeviceEventRepositoryTests.java:54)
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.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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.sql.SQLSyntaxErrorException: incompatible data type in conversion
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.throwError(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setParameter(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.setObject(Unknown Source)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:454)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:238)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:169)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.doSetValue(ArgumentPreparedStatementSetter.java:66)
at org.springframework.jdbc.core.ArgumentPreparedStatementSetter.setValues(ArgumentPreparedStatementSetter.java:47)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:875)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:870)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 34 more
Caused by: org.hsqldb.HsqlException: incompatible data type in conversion
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.types.DateTimeType.convertJavaToSQL(Unknown Source)
... 44 more
I think your columns/parameters are misaligned. The date_received specifically doesn't seem to have a corresponding parameter so it's trying to convert a float (RSSI) into a timestamp
I have a web application where the server returns any results in JSON format. For creating the JSON, I use the codehaus Jackson ObjectWriter, version 1.9.8.
The problem I'm having that sometimes there is an error, in the mapping, and from then on all server calls result in an error. I haven't been able to determine what causes the error, I did discover the origin.
When the exception occurs, the server returns "(was java.lang.ArrayIndexOutOfBoundsException) (through reference chain: com.onior.modm.restlet.helpers.ServiceResult["success"])", which means that the exception thrown in 'toJSON' was catched and mapped to JSON by 'toRepresentation', otherwise it would have returned empty.
I just don't know why it is sometimes failing. I will be able to use the application all morning without problems, and then suddenly I will get this error. It happens on different calls, but these calls will succeed at other times. From my point of view it seems quite random, but maybe someone can help me see the light? :)
The server result that is being mapped:
public class ServiceResult<T> {
private boolean success;
private T results = null;
private ModmServiceStatus message = null;
public ServiceResult() {
}
public ServiceResult(T results) {
this.success = true;
this.results = results;
}
public ServiceResult(boolean success, ModmServiceStatus message) {
this.success = success;
this.message = message;
}
public ServiceResult(ServiceError error) {
this(false, new ModmServiceStatus(error));
}
public static ServiceResult<ModmServiceStatus> serviceException(
ServiceError error) {
return new ServiceResult<ModmServiceStatus>(false,
new ModmServiceStatus(error.getCode(), error.getDescription()));
}
public static ServiceResult<ModmServiceStatus> dbError() {
return ServiceResult
.serviceException(ServiceError.GENERIC_DATABASE_ERROR);
}
public static ServiceResult<ModmServiceStatus> invalidJson() {
return ServiceResult
.serviceException(ServiceError.GENERIC_INVALID_JSON);
}
public static ServiceResult<ModmServiceStatus> missingEntity() {
return ServiceResult .serviceException(ServiceError.GENERIC_MISSING_OR_INCOMPLETE_ENTITY);
}
public static ServiceResult<ModmServiceStatus> entityNotFound() {
return ServiceResult
.serviceException(ServiceError.GENERIC_ENTITY_NOT_FOUND);
}
public static ServiceResult<ModmServiceStatus> entityDeleted(String entity) {
return new ServiceResult<ModmServiceStatus>(true,
new ModmServiceStatus(0, entity + " deleted."));
}
}
The mapping:
public class RestUtils {
private static final boolean PRETTY_PRINT = true;
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final ObjectWriter OBJECT_WRITER = (PRETTY_PRINT ? OBJECT_MAPPER
.writerWithDefaultPrettyPrinter() : OBJECT_MAPPER.writer());
#SuppressWarnings("unchecked")
public static <T> JacksonRepresentation<T> toJSON(T t) throws IOException {
JsonRepresentation jsonRepresentation = null;
JacksonRepresentation<T> jacksonRepresentation = null;
jsonRepresentation = new JsonRepresentation(
OBJECT_WRITER.writeValueAsString(t)); // Origin of incidental
// server error
jacksonRepresentation = new JacksonRepresentation<T>(
jsonRepresentation, (Class<T>) t.getClass());
return jacksonRepresentation;
}
public static <T> Representation toRepresentation(ServiceResult<T> ss) {
Representation representation = null;
try {
representation = RestUtils.toJSON(ss);
} catch (IOException jsonException) {
jsonException.printStackTrace();
try {
jsonException.printStackTrace();
representation = RestUtils.toJSON(jsonException.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
return representation;
}
}
The call:
RestUtils.toRepresentation(new ServiceResult<List<Group>>(groups));
The exception with stacktrace:
org.codehaus.jackson.map.JsonMappingException: (was java.lang.ArrayIndexOutOfBoundsException) (through reference chain: com.onior.modm.restlet.helpers.ServiceResult["success"])
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218)
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183)
at org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158)
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
at org.codehaus.jackson.map.ObjectWriter._configAndWriteValue(ObjectWriter.java:456)
at org.codehaus.jackson.map.ObjectWriter.writeValueAsString(ObjectWriter.java:393)
at com.onior.modm.restlet.helpers.RestUtils.toJSON(RestUtils.java:52)
at com.onior.modm.restlet.helpers.RestUtils.toRepresentation(RestUtils.java:71)
at com.onior.modm.restlet.resources.GroupCollectionResource.toJsonRead(GroupCollectionResource.java:191)
at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:506)
at org.restlet.resource.ServerResource.get(ServerResource.java:707)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:589)
at org.restlet.resource.ServerResource.doNegotiatedHandle(ServerResource.java:649)
at org.restlet.resource.ServerResource.doConditionalHandle(ServerResource.java:348)
at org.restlet.resource.ServerResource.handle(ServerResource.java:952)
at org.restlet.resource.Finder.handle(Finder.java:246)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:431)
at org.restlet.routing.Router.handle(Router.java:648)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:431)
at org.restlet.routing.Router.handle(Router.java:648)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:155)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.engine.CompositeHelper.handle(CompositeHelper.java:211)
at org.restlet.engine.application.ApplicationHelper.handle(ApplicationHelper.java:84)
at org.restlet.Application.handle(Application.java:381)
at org.restlet.ext.servlet.ServletAdapter.service(ServletAdapter.java:206)
at org.restlet.ext.spring.RestletFrameworkServlet.doService(RestletFrameworkServlet.java:124)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ArrayIndexOutOfBoundsException
at org.codehaus.jackson.impl.WriterBasedGenerator.writeRaw(WriterBasedGenerator.java:577)
at org.codehaus.jackson.util.DefaultPrettyPrinter$Lf2SpacesIndenter.writeIndentation(DefaultPrettyPrinter.java:279)
at org.codehaus.jackson.util.DefaultPrettyPrinter.beforeObjectEntries(DefaultPrettyPrinter.java:98)
at org.codehaus.jackson.impl.WriterBasedGenerator._writePPFieldName(WriterBasedGenerator.java:410)
at org.codehaus.jackson.impl.WriterBasedGenerator._writeFieldName(WriterBasedGenerator.java:340)
at org.codehaus.jackson.impl.WriterBasedGenerator.writeFieldName(WriterBasedGenerator.java:217)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:444)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
... 58 more
Got the exact same ArrayIndexOutOfBoundsException with Jackson 1.9.9
After investigating, our root cause was a shared PrettyPrinter used by multiple threads.
If you look in the Jackson code for the DefaultPrettyPrinter, you will see:
/**
* Number of open levels of nesting. Used to determine amount of
* indentation to use.
*/
protected int _nesting = 0;
_nesting ends up being used to access arrays. This variable is incremented and decremented when processing object. If multiple threads decrements it, it may end up negative causing the ArrayIndexOutOfBoundsException. Once negative, it will not be ever increased again because the exception will be generated before reaching a piece of code that would increment it.
In your code, I see you have a static object writer. You probably end up with a single instance of the DefaultPrettyPrinter. If your application can concurrently produce json object, given enough time, you will get the exception.
Stéphan
I'm having a tough time figuring out the issue with Serialization in hadoop. Here's my class -
public class CrawlerTweet implements Serializable, Writable {
private static final long serialVersionUID = 1L;
private String keywords;
private List<TweetStatus> tweets;
private long queryTime = 0;
public CrawlerTweet() {}
public CrawlerTweet(String keys, List<TweetStatus> tweets, long queryTime){
this.keywords = keys;
this.tweets = tweets;
this.queryTime = queryTime;
}
public static CrawlerTweet read(DataInput in) throws IOException {
CrawlerTweet ts= new CrawlerTweet();
ts.readFields(in);
return ts;
}
#Override
public void readFields(DataInput din) throws IOException {
queryTime = din.readLong();
keywords = din.readLine();
tweets.clear();
IntWritable size = new IntWritable();
size.readFields(din);
int n = size.get();
while(n -- > 0) {
TweetStatus ts = new TweetStatus();
ts.readFields(din);
tweets.add(ts);
}
}
#Override
public void write(DataOutput dout) throws IOException {
dout.writeChars(keywords);
dout.writeLong(queryTime);
IntWritable size = new IntWritable(tweets.size());
size.write(dout);
for (TweetStatus ts : tweets)
ts.write(dout);
}
public String getKeywords(){
return keywords;
}
public List<TweetStatus> getTweets(){
return tweets;
}
public long getQueryTime(){
return queryTime;
}
}
If I implment both Serizable n WRitable interfaces, I get following exception,
java.lang.ClassNotFoundException: mydat.twitter.dto.CrawlerTweet
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)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:249)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:601)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1572)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1493)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1729)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1326)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at focusedCrawler.util.storage.socket.ServerConnectionHandler.buildRequestObject(ServerConnectionHandler.java:136)
at focusedCrawler.util.storage.socket.ServerConnectionHandler.run(ServerConnectionHandler.java:340)
And, if I implment Writable only, I get NotSerializableException -
Erro de comunicacao: bigdat.twitter.dto.CrawlerTweet
Dormindo 5 mls
`[21/JUN/2013:11:23:39] [SocketAdapterFactory] [produce] [hadoop22:3190]
Erro de comunicacao: bigdat.twitter.dto.CrawlerTweet
java.io.NotSerializableException: bigdat.twitter.dto.CrawlerTweet
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.serializeParamObject(StorageRemoteAdapter.java:113)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.defaultMethod(StorageRemoteAdapter.java:205)
at focusedCrawler.util.storage.socket.StorageRemoteAdapter.insert(StorageRemoteAdapter.java:289)
at focusedCrawler.util.storage.distribution.StorageRemoteAdapterReconnect.insert(StorageRemoteAdapterReconnect.java:213)
at bigdat.twitter.crawler.CrawlTwitter.download(Unknown Source)
at bigdat.twitter.crawler.CrawlTwitter.run(Unknown Source)
Further information extracted from comments:
CrawlerTweet is packaged in BDAnalytics16.jar file.
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/home/rgupta/bdAnalytics/lib/*
hadoop jar $jarpath/BDAnalytics16.jar bigdat.twitter.crawler.CrawlTwitter \
$crwlInputFile > $logsFldr/crawler_$1.log 2>&1 &
Help will be much appreciated!
Thx!
I have a slight problem that I don't know how to solve. Could you help me please?
When I am trying to persist entity I get next exception:
12:47:39,398 ERROR [org.black.dmitriy.entityHome.ScheduleHome] (http--127.0.0.1-8080-1) javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1333) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:859) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.seam.persistence.EntityManagerInvocationHandler.invoke(EntityManagerInvocationHandler.java:46) [jboss-seam.jar:2.3.0.Final]
at $Proxy81.persist(Unknown Source) at org.jboss.seam.framework.EntityHome.persist(EntityHome.java:84) [jboss-seam.jar:2.3.0.Final]
at org.black.dmitriy.entityHome.ConversationHome.tryPersist(ConversationHome.java:147) [ejb.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.core.ConversationInterceptor.aroundInvoke(ConversationInterceptor.java:65) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.util.Work.workInTransaction(Work.java:61) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:186) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:104) [jboss-seam.jar:2.3.0.Final]
at org.black.dmitriy.entityHome.ScheduleHome_$$_javassist_seam_8.tryPersist(ScheduleHome_$$_javassist_seam_8.java) [ejb.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04]
at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04]
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.parser.AstValue.invoke(AstValue.java:96) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final]
at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) [jboss-seam.jar:2.3.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:397) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_04]
I use seam 2.3, hibernate. I have one insert statement in my import.sql file:
INSERT INTO Schedules (id, name, dayCount, lessonCount, firstTermSize, secondTermSize, subgroupSize) VALUES(1, '2012/2013', 5, 8, 9, 9, 18)
which inserts one enity into table Schedules.
Then I create new Schedule entity throw web page using EntityHome
#Name("scheduleHome")
#Scope(ScopeType.CONVERSATION)
public class ScheduleHome extends ConversationHome<Schedule> {
private static final long serialVersionUID = 1L;
public ScheduleHome() {
}
#Override
protected boolean isUnique() {
Schedule schedule = getInstance();
Schedule foundSchedule = ScheduleDAO.instance().getByName(schedule.getName());
if ((foundSchedule != null) && (!foundSchedule.equals(schedule))) {
showExistsErrorMessage(getInstance().getName());
return false;
}
return true;
}
#Override
protected Schedule createInstance() {
return new Schedule();
}
#Override
public String getEditOutcome() {
return "scheduleEdit";
}
#Override
protected void prepareEntityForSaving() {
}
}
and the superclass
public abstract class ConversationHome<T> extends EntityHome<T> {
private static final long serialVersionUID = 1L;
private String parentView;
public boolean isParentViewExists() {
return parentView != null && parentView.length() > 0;
}
public void setParentView(String parentView) {
this.parentView = parentView;
}
public String getParentView() {
return parentView;
}
public abstract String getEditOutcome();
protected abstract void prepareEntityForSaving();
protected abstract boolean isUnique();
#Override
#Create
public void create() {
create(false);
}
protected void create(boolean createNestedConversation) {
Conversation conversation = Conversation.instance();
if (!createNestedConversation && conversation.isLongRunning()) {
getLog().debug("conversation already started, nested will not create(isLongRunning = #0, isNested = #1)", conversation.isLongRunning(), conversation.isNested());
} else {
conversation.begin(false, conversation.isLongRunning());
conversation.changeFlushMode(FlushModeType.MANUAL);
getLog().debug("create(isLongRunning = #0, isNested = #1, id = #2)", conversation.isLongRunning(), conversation.isNested(), conversation.getId());
}
super.create();
}
private boolean init(Long id) {
FacesContext context = FacesContext.getCurrentInstance();
setParentView(Pages.getViewId(context));
if (id != null) {
setId(id);
try {
getInstance();
getLog().debug("instance initialized #0", getInstance());
} catch (EntityNotFoundException e) {
getLog().error(e);
return false;
}
}
return true;
}
public String startEdit(Long id) {
getLog().debug("start editing #0", id);
if (init(id)) {
return getEditOutcome();
} else {
return cancel();
}
}
public String cancel() {
if (isManaged()) {
getEntityManager().refresh(getInstance());
}
return returnToParent();
}
#End
protected String returnToParent() {
if (isParentViewExists()) {
Conversation conversation = Conversation.instance();
getLog().debug("end conversation(id = #0, isLongRunning = #1, isNested = #2)",
conversation.getId(), conversation.isLongRunning(), conversation.isNested());
conversation.end(true);
return getParentView();
} else {
clearInstance();
return null;
}
}
public String tryPersist() {
if (isUnique()) {
try {
prepareEntityForSaving();
String outcome = persist();
if (!"failed".equals(outcome)) {
return returnToParent();
}
} catch (Exception e) {
getLog().error(getInstance(), e);
showSaveErrorMessage(e);
}
}
return "failed";
}
}
and when i try to persist it i get this exception. and message on web page
Save error with message: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1]
It seams that hibernate set id property to 1, but I already have entity with id = 1, because I manually created it throw import.sql.
Here is my Schedule entity :
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "Schedules")
public class Schedule {
#Id
#GeneratedValue
#Column(name = "id", nullable = false)
private Long id;
#NotNull
#Column(name = "name", nullable = false, length = 40)
private String name;
#Column(name = "dayCount")
private int dayCount = 5;
#Column(name = "lessonCount")
private int lessonCount = 8;
#Column(name = "firstTermSize")
private int firstTermSize = 9;
#Column(name = "secondTermSize")
private int secondTermSize = 9;
#Column(name = "subgroupSize")
private int subgroupSize = 18;
#OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Faculty.class)
private List<Faculty> faculties = new ArrayList<>();
#OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Building.class)
private List<Building> buildings = new ArrayList<>();
public Schedule() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDayCount() {
return dayCount;
}
public void setDayCount(int dayCount) {
this.dayCount = dayCount;
}
public int getLessonCount() {
return lessonCount;
}
public void setLessonCount(int lessonCount) {
this.lessonCount = lessonCount;
}
public int getFirstTermSize() {
return firstTermSize;
}
public void setFirstTermSize(int firstTermSize) {
this.firstTermSize = firstTermSize;
}
public int getSecondTermSize() {
return secondTermSize;
}
public void setSecondTermSize(int secondTermSize) {
this.secondTermSize = secondTermSize;
}
public int getSubgroupSize() {
return subgroupSize;
}
public void setSubgroupSize(int subgroupSize) {
this.subgroupSize = subgroupSize;
}
public List<Faculty> getFaculties() {
return faculties;
}
public void setFaculties(List<Faculty> faculties) {
this.faculties = faculties;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Schedule)) {
return false;
}
Schedule other = (Schedule) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
#Override
public String toString() {
return this.name;
}
}
As you can see there is #GeneratedValue annotation on id property, so I think that hibernate should generate id himself and hibernate should know that there is entity in database with id = 1, and set id in new entity = 2. But Hibernate sets id in new entity to 1.
Could you halp me please?
The problem was how hibernate generates your id's, it starts from 1. When it assigns 1 to an object before saving it into database, it sees a row with same id already exists in the database and causes the exception. The simple and natural solution of this problem is simply to restrict hibernate, so that it can not assign 1 as an id to any object of the concerning class (in your case).
Solution for mySql:
If you are using mySql, you can create table manually and set the auto increment like:
CREATE TABLE IF NOT EXISTS `testTable` (
`id` number(11) NOT NULL AUTO_INCREMENT,
...,
...,
...,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; //assigning id by hibernate, will start from 2.
And in your domain class you can have id annotated like bellow:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
public long getId() {
....
}
GenerationType.AUTO by default uses auto increment in mySql. and after setting AUTO_INCREMENT=2 hibernate will start assigning id's from 2 (hence 1 is skipped).
Solution for Oracle:
The same thing for oracle can be done if you restrict hibernate use a "sequence" and you set the initial point of the sequence as your wish. You can create a sequence to be start from 2 and increment by 1 like bellow:
create sequence idSequence
start with 2
increment by 1
maxvalue 9999999999999;
And you can specify your sequence to be used to generate id's of your domain class's object like bellow:
#Id
#SequenceGenerator(name = "idGeneratorSeq", sequenceName = "idSequence")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "idGeneratorSeq")
#Column(name = "ID")
public long getId() {
....
}
And your problem is sovled.
Do the following steps before calling persist() method.
First detach your current instance
getEntityManager().detach(getInstance());
Now set its Id to null
getInstance().setId(null);
Now persist
String outcome = persist();