Okay, i am very very very new to Hibernate/Spring. I had to upgrade existing code from Hibernate 2 - Hibernate 4 and Spring 1 - Spring 3.
I keep getting this exception when trying to call saveOrUpdate when passing more than one message to the database (it works fine when I only send one message):
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:686)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:239)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:109)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:728)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:720)
at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:423)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:264)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:136)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:728)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:720)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:716)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at $Proxy9.saveOrUpdate(Unknown Source)
I have googled till I am blue in the face! I have tried to use merge(). This does not give the exception, but merge inserts NULL values into the Database.
I have tried to use evict(), flush(), same error.
This is the method that causes the error:
public void saveOrUpdate(Object obj) {
Session session = null;
SessionFactory sf = getSessionFactory();
try {
try {
session = sf.getCurrentSession();
} catch (Exception e) {
session = sf.openSession();
}
System.out.println("Object: " + obj);
session.beginTransaction();
session.saveOrUpdate(obj);
session.getTransaction().commit();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
Any help would be greatly appreciated!
Can you please provide the mappings and the code which calls the saveOrUpdate methods. It looks like the error is in the code which calls the saveOrUpdate
I solved it :)
I don't know if its the best solution, but it works for me and after 2 solid days of struggling I'm happy!
I removed Cascade from the parent object and explicitly called saveOrUpdate on parent and then on the children.
Thanks everyone for the help :)
Related
I have a Grails app where controller calls transactional service. The service has the following body
def rep = Rep.findById(2708280)
def r = Rep.findById(2708280)
r.accountNumber = "123423565476"
r.save(failOnError: true)
def list = Rep.findAllByRtnAndAccountNumber(
rep.rtn, rep.accountNumber)
When the last line in the method is called, I get the following hibernate exception:
ERROR an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) [AssertionFailure]
org.hibernate.AssertionFailure: collection [com.mydomain.InnerObject.assignedTests] was not processed by flush()
at org.hibernate.engine.CollectionEntry.postFlush(CollectionEntry.java:228)
at org.hibernate.event.def.AbstractFlushingEventListener.postFlush(AbstractFlushingEventListener.java:352)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:65)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1709)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.FindAllByPersistentMethod$1.doInHibernate(FindAllByPersistentMethod.java:113)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeFind(HibernateTemplate.java:348)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.FindAllByPersistentMethod.doInvokeInternalWithExpressions(FindAllByPersistentMethod.java:73)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractClausedStaticPersistentMethod.doInvokeInternal(AbstractClausedStaticPersistentMethod.java:543)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractClausedStaticPersistentMethod.doInvokeInternal(AbstractClausedStaticPersistentMethod.java:417)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractStaticPersistentMethod.invoke(AbstractStaticPersistentMethod.java:79)
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractStaticPersistentMethod.invoke(AbstractStaticPersistentMethod.java:72)
at sun.reflect.GeneratedMethodAccessor9819.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:233)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:56)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:58)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:141)
at org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2.doCall(GormStaticApi.groovy:102)
at org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2.call(GormStaticApi.groovy)
at org.codehaus.groovy.runtime.metaclass.ClosureStaticMetaMethod.invoke(ClosureStaticMetaMethod.java:62)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.invoke(StaticMetaMethodSite.java:46)
at org.codehaus.groovy.runtime.callsite.StaticMetaMethodSite.call(StaticMetaMethodSite.java:91)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at com.mydomaint.MyService.$tt__process(MyService.groovy:118)
where 'com.mydomain.InnerObject' is an inner object of my domain object above.
static belongsTo = [owner: InnerObject]
InnerObject owner
and assignedTests is a property of InnerObject domain:
static hasMany = [assignedVouchers: AssignedTests]
Is there anything I am missing here? What does this exception mean?
That happens probably because you have two objects of the same instance in the session with different values.
rep is unmodified and r is modified (and persisted)
When you call list, Hibernate tries to flush the session and it gets confused
at org.hibernate.engine.CollectionEntry.postFlush(CollectionEntry.java:228)
at org.hibernate.event.def.AbstractFlushingEventListener.postFlush(AbstractFlushingEventListener.java:352)
at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:65)
at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1709)
Instead you could try to hold the parameters you pass to the list in separate variables. Try that:
def r = Rep.findById(2708280)
def p1 = r.rtn
def p2 = r.accountNumber
r.accountNumber = "123423565476"
r.save(failOnError: true)
def list = Rep.findAllByRtnAndAccountNumber(p1, p2)
In envers (persistence.xml), I enabled the strategy for table partitioning, according to the development guide: http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch15.html#envers-partitioning
The class: ValidityAuditStrategy, throws RuntimeException when there is no audit record. This exception occurs when the Envers try to update an audit record with a date of final revision (revend_tstmp), but this audit record does not exist.
The database of my application receives data load from external applications and is not possible change these external applications to include their audit records.
I have no chance to handle this exception (I don't know how).
In method ValidityAuditStrategy#updateLastRevision:
if (l.size() == 1) {
//... doStuff - OK
} else {
throw new RuntimeException("Cannot find previous revision for entity " + auditedEntityName + " and id " + id);
}
In method ValidityAuditStrategy#perform:
if ( rowCount != 1 )
throw new RuntimeException("Cannot update previous revision for entity " + auditedEntityName + " and id " + id);
A similar issue occurred in this link: https://developer.jboss.org/thread/160195?tstart=0 but had no solution.
It's possible apply a workaround?
I use hibernate-envers-4.1.3-Final version.
Log:
2015-07-17 10:23:28,653 DEBUG [-] [org.hibernate.SQL] (http-/0.0.0.0:8080-5) update MY_ENTITY_AUD set ID_REV_FINAL=?, DATE_HOUR_REV_FINAL=? where ID_ENTITY=? and ID_REV <> ? and ID_REV_FINAL is null
2015-07-17 10:23:28,677 TRACE [-] [org.hibernate.type.descriptor.sql.BasicBinder] (http-/0.0.0.0:8080-5) binding parameter [1] as [INTEGER] - 422
2015-07-17 10:23:28,677 TRACE [-] [org.hibernate.type.descriptor.sql.BasicBinder] (http-/0.0.0.0:8080-5) binding parameter [2] as [TIMESTAMP] - Thu Jul 17 10:23:28 BRT 2015
2015-07-17 10:23:28,677 TRACE [-] [org.hibernate.type.descriptor.sql.BasicBinder] (http-/0.0.0.0:8080-5) binding parameter [3] as [INTEGER] - 12345
2015-07-17 10:23:28,678 TRACE [-] [org.hibernate.type.descriptor.sql.BasicBinder] (http-/0.0.0.0:8080-5) binding parameter [4] as [INTEGER] - 422
2015-07-17 10:23:28,803 ERROR [-] [org.hibernate.AssertionFailure] (http-/0.0.0.0:8080-5) HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): java.lang.RuntimeException: Cannot update previous revision for entity my.package.MyEntity_AUD and id 12345
2015-07-17 10:23:28,841 WARN [-] [com.arjuna.ats.arjuna] (http-/0.0.0.0:8080-5) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffffac1c045d:-3a5600e4:55a7c120:131, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization#5619c5a3 >: org.hibernate.AssertionFailure: Unable to perform beforeTransactionCompletion callback
at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:754) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:338) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:490) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorNonTrackingImpl.beforeCompletion(SynchronizationCallbackCoordinatorNonTrackingImpl.java:114) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:53) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76)
at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:273)
at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:93)
at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)
at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1189)
at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:126)
at com.arjuna.ats.jbossatx.BaseTransactionManagerDelegate.commit(BaseTransactionManagerDelegate.java:75)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.endTransaction(CMTTxInterceptor.java:92) [jboss-as-ejb3-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
...
Caused by: java.lang.RuntimeException: Cannot update previous revision for entity entity my.package.MyEntity_AUD and id 12345
at org.hibernate.envers.strategy.ValidityAuditStrategy.perform(ValidityAuditStrategy.java:210) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.envers.synchronization.work.AbstractAuditWorkUnit.perform(AbstractAuditWorkUnit.java:76) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.envers.synchronization.AuditProcess.executeInSession(AuditProcess.java:116) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.envers.synchronization.AuditProcess.doBeforeTransactionCompletion(AuditProcess.java:155) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.envers.synchronization.AuditProcessManager$1.doBeforeTransactionCompletion(AuditProcessManager.java:62) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:748) [hibernate-core-4.1.3-Final.jar:4.1.3-Final]
... 90 more
In persistence.xml existing a property to specify a custom AuditStrategey: org.hibernate.envers.audit_strategy.
Change,
From:
<property name="org.hibernate.envers.audit_strategy" value="org.hibernate.envers.strategy.ValidityAuditStrategy"/>
To:
<property name="org.hibernate.envers.audit_strategy" value="com.app.your.pack.YourCustomValidityAuditStrategy"/>
So now you can extend ValidityAuditStrategy and override perform() to not throw a RuntimeException when there is no previous revision for the entity, like this:
public class YourCustomValidityAuditStrategy extends ValidityAuditStrategy {
private final Log logger = LogFactory.getLog(getClass());
#Override
public void perform(Session session, String entityName, AuditConfiguration auditCfg, Serializable id, Object data, Object revision) {
try {
super.perform(session, entityName, auditCfg, id, data, revision);
} catch (RuntimeException re) {
if (logger.isDebugEnabled()) {
logger.debug("IGNORE RuntimeException: Cannot update previous revision for entity.", re);
}
}
}
Overriding just the perform method and catching the RuntimeException won't help you as the code throwing the RuntimeException is enclosed in an anonymous class of type BeforeTransactionCompletionProcess and is executed later.
The ValidityAuditStrategy is not very flexible so the only solution i see is ugly but should work : you must copy the entire ValidityAuditStrategy code in a custom class and catch the RuntimeException in the BeforeTransactionCompletionProcess anonymous class. Then specify your custom class in the persistence.xml :
<property name="org.hibernate.envers.audit_strategy "value="com.app.xxx.CustomValidityAuditStrategy"/>
The perform() method should look like the following :
#Override
public void perform(
final Session session,
final String entityName,
final EnversService enversService,
final Serializable id,
final Object data,
final Object revision) {
final AuditEntitiesConfiguration audEntitiesCfg = enversService.getAuditEntitiesConfiguration();
final String auditedEntityName = audEntitiesCfg.getAuditEntityName( entityName );
final String revisionInfoEntityName = enversService.getAuditEntitiesConfiguration().getRevisionInfoEntityName();
// Save the audit data
session.save( auditedEntityName, data );
// Update the end date of the previous row.
//
// When application reuses identifiers of previously removed entities:
// The UPDATE statement will no-op if an entity with a given identifier has been
// inserted for the first time. But in case a deleted primary key value was
// reused, this guarantees correct strategy behavior: exactly one row with
// null end date exists for each identifier.
final boolean reuseEntityIdentifier = enversService.getGlobalConfiguration().isAllowIdentifierReuse();
if ( reuseEntityIdentifier || getRevisionType( enversService, data ) != RevisionType.ADD ) {
// Register transaction completion process to guarantee execution of UPDATE statement after INSERT.
( (EventSource) session ).getActionQueue().registerProcess( new BeforeTransactionCompletionProcess() {
#Override
public void doBeforeTransactionCompletion(final SessionImplementor sessionImplementor) {
final Queryable productionEntityQueryable = getQueryable( entityName, sessionImplementor );
final Queryable rootProductionEntityQueryable = getQueryable(
productionEntityQueryable.getRootEntityName(), sessionImplementor
);
final Queryable auditedEntityQueryable = getQueryable( auditedEntityName, sessionImplementor );
final Queryable rootAuditedEntityQueryable = getQueryable(
auditedEntityQueryable.getRootEntityName(), sessionImplementor
);
final String updateTableName;
/*commented code*/
...
/*comment the following piece of code*/
/*if ( rowCount != 1 && ( !reuseEntityIdentifier || ( getRevisionType( enversService, data ) != RevisionType.ADD ) ) ) {
throw new RuntimeException(
"Cannot update previous revision for entity " + auditedEntityName + " and id " + id
);
}*/
}
});
}
sessionCacheCleaner.scheduleAuditDataRemoval( session, data );
}
As i said its ugly...
Setting org.hibernate.envers.allow_identifier_reuse: true helped in my scenario.
Not exactly answers the original question, but on the outside looks the same: Cannot update previous revision for entity my.package.MyEntity_AUD and id caa4ce8e.
I am using hibernate-envers-5.4.1 and for whatever reason (probably some buggy import in the past) suddenly faced the same error.
Direct query to the database select * from myentity_aud where id='caa4ce8e' resulted in:
rev revend revtype id ...
2121736 NULL 0 caa4ce8e ...
2121737 NULL 1 caa4ce8e ...
2121738 NULL 1 caa4ce8e ...
-- as seen, revend is NULL for all records.
The issue is: envers expects only one (the latest) to be NULL, all the rest must have the "overriding" rev to be set as revend.
So, to fix this particular case, it was enough to update to:
rev revend revtype id ...
2121736 2121737 0 caa4ce8e ...
2121737 2121738 1 caa4ce8e ...
2121738 NULL 1 caa4ce8e ...
and after that everything worked like a charm.
However, if you have millions of such records, you may want to write some script which will take care of them automatically.
I am using Spring Hibernate with app engine and cloudSQL for my project but i am getting one error frequently. This occurs when application becomes ideal for sometimes.
For every query (fetching or save/update to database), i open session and close session after its use. like this --
My code for database fetching is
try{
Session session = getSessionFactory().openSession();
if(session != null)
{
List<Account> accounts = session.createQuery("from " + this.clazz.getName() + " where subDomainName = '"+subDomain+"'").list();
session.close();
if(accounts != null)
{
if(accounts.size()>0){
return accounts.get(0);
}
else{
return null;
}
}
else
{
return null;
}
}
else {
return null;
}
}
catch(Exception e){
log.info("Error in retriving subdomain details :: in Account Dao");
return null;
}
I am using Autowired structuring. but when application becomes ideal for sometime and after some time when i refresh page its display the error as Stream Closed of CloudSQL on app engine, error is shown below...
Error is :
6 Jan, 2014 6:21:04 AM com.google.appengine.repackaged.org.apache.http.impl.client.DefaultRequestDirector handleResponse
WARNING: Authentication error: Unable to respond to any of these challenges: {bearer=WWW-Authenticate: Bearer realm="https://www.google.com/accounts/AuthSubRequest", error=invalid_token}
6 Jan, 2014 6:21:04 AM com.google.appengine.api.rdbms.dev.LocalRdbmsServiceRemoteDriver openConnection
WARNING: openConnection
java.sql.SQLException: Stream closed
at com.google.cloud.sql.jdbc.internal.googleapi.RpcGoogleApi.newOpenConnectionIOException(RpcGoogleApi.java:187)
at com.google.cloud.sql.jdbc.internal.googleapi.RpcGoogleApi.openConnection(RpcGoogleApi.java:105)
at com.google.appengine.api.rdbms.dev.LocalRdbmsServiceRemoteDriver.openConnection(LocalRdbmsServiceRemoteDriver.java:206)
at com.google.appengine.api.rdbms.dev.LocalRdbmsService.openConnection(LocalRdbmsService.java:119)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.callInternal(ApiProxyLocalImpl.java:498)
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:452)
at com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:430)
at java.util.concurrent.Executors$PrivilegedCallable$1.run(Executors.java:461)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.concurrent.Executors$PrivilegedCallable.call(Executors.java:458)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.io.IOException: Stream closed
at java.util.zip.GZIPInputStream.ensureOpen(GZIPInputStream.java:42)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:85)
For this to engage app engine and cloudSQL i have wriiten cron job of certains request but this is not feasible solution, i can not gets why cloudSQL closes its stream for app engine.
So, I'm writing code that will create user accounts in AD LDS. I can create the user, but the account is disabled.
I want the user to be active and to be able to change their password. I've tried some of the things suggested in this post, but it hasn't helped me.
Here's my code:
ctx = getConnection(adminUser, adminPassword);
// Create attributes for the new user
Attributes attributes = new BasicAttributes(true);
// Main attributes for user
attributes.put("objectClass", "user");
attributes.put("name", user.getFullName());
attributes.put("ms-DS-User-Account-Control-Computed",
Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED));
try {
ctx.createSubcontext(getDistinguishedName(user.getFullName()),
attributes);
System.out.println("User successfully added!");
} catch (NamingException e) {
e.printStackTrace();
}
When I run this, I get the following error:
javax.naming.directory.NoSuchAttributeException: [LDAP: error code 16
- 00000057: LdapErr: DSID-0C090D11, comment: Error in attribute conversion operation, data 0, v23f0remaining name 'CN=Samuel
King,CN=Users,CN=Agents,DC=CHESA,DC=local' at
com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source) at
com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source) at
com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source) at
com.sun.jndi.ldap.LdapCtx.c_createSubcontext(Unknown Source) at
com.sun.jndi.toolkit.ctx.ComponentDirContext.p_createSubcontext(Unknown
Source) at
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.createSubcontext(Unknown
Source) at
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.createSubcontext(Unknown
Source) at
javax.naming.directory.InitialDirContext.createSubcontext(Unknown
Source) at
com.ceiwc.ActiveDirectory.createUserAccount(ActiveDirectory.java:114)
at com.ceiwc.TestAD.main(TestAD.java:24)
If I change the line where I'm updating the ms-DS-User-Account-Control-Computed to:
attributes.put("ms-DS-User-Account-Control-Computed", UF_NORMAL_ACCOUNT
+ UF_PASSWORD_EXPIRED);
i get the following error:
javax.naming.directory.InvalidAttributeValueException: Malformed
'ms-DS-User-Account-Control-Computed' attribute value; remaining name
'CN=Samuel King,CN=Users,CN=Agents,DC=CHESA,DC=local' at
com.sun.jndi.ldap.LdapClient.encodeAttribute(Unknown Source) at
com.sun.jndi.ldap.LdapClient.add(Unknown Source) at
com.sun.jndi.ldap.LdapCtx.c_createSubcontext(Unknown Source) at
com.sun.jndi.toolkit.ctx.ComponentDirContext.p_createSubcontext(Unknown
Source) at
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.createSubcontext(Unknown
Source) at
com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.createSubcontext(Unknown
Source) at
javax.naming.directory.InitialDirContext.createSubcontext(Unknown
Source) at
com.ceiwc.ActiveDirectory.createUserAccount(ActiveDirectory.java:116)
at com.ceiwc.TestAD.main(TestAD.java:24)
So, what am I doing wrong? Is this the proper way to activate the account? Does someone have any code to help me out?
Thanks!
NuAlphaMan,
I think, that the exception has something to do with the fact that you use CN as the name of the attribute instead of Ldap-Display-Name which is msDS-User-Account-Control-Computed. The description could be found here http://msdn.microsoft.com/en-us/library/windows/desktop/ms677840(v=vs.85).aspx.
As to the second question of how to activate an account, I've found that there is an attribute userAccountControl (http://msdn.microsoft.com/en-us/library/windows/desktop/ms680832(v=vs.85).aspx#win_2008_r2) and the value 0x00000002 (ADS_UF_ACCOUNTDISABLE) that can disable an account. The only thing that crosses my mind is to try to read the value and flip the bit.
Regards, Dmitry
NoSuchAttributeException: "Indicates that the attribute specified in the modify or compare operation does not exist in the entry."
Malformed 'ms-DS-User-Account-Control-Computed' attribute value: means wrong attribute type.
here is my working example, that i check with ActiveDirectory 2008:
public void mapToContext(int userAccountControl, DirContextAdapter context) {
context.setAttributeValue("userAccountControl", disableAccount(userAccountControl));
}
private String disableAccount(int userAccountControl) {
userAccountControl |= AccountControlFlags.ACCOUNTDISABLE;
return String.valueOf(userAccountControl);
}
I am trying to fire a subquery from hibernate, but it is showing NPE:-(Anyone know how to resolve it? Below is the code:
DetachedCriteria criteria = DetachedCriteria.forClass(My.class,"A");
criteria.createAlias("A.a", "a");
criteria.createAlias("A.b", "b");
if(cValue !=null && cValue.size()>0){
criteria.add(Restrictions.in("b.c", cValue));
}
if(StringUtils.isNotEmpty(commodityList)){
DetachedCriteria commCriteria = DetachedCriteria.forClass(My.class,"A1");
commCriteria.createAlias("A1.a", "a1");
commCriteria.add(Restrictions.in("a1.name", commodityList.split(",")));
criteria.add(Subqueries.propertyIn("b.c", commCriteria));
}
criteria.addOrder(Order.asc("b.c"));
return getHibernateTemplate().findByCriteria(criteria);
Stack Trace:
java.lang.NullPointerException
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getProjectedTypes(CriteriaQueryTranslator.java:318)
at org.hibernate.criterion.SubqueryExpression.toSqlString(SubqueryExpression.java:56)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:334)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:67)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1550)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1065)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1055)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1048)
at com.boeing.kmapi.base.skillset.dao.impl.EssSkillsetCommMapDAOImpl.getEssSkillsetCommMapforSkillsetIdList(EssSkillsetCommMapDAOImpl.java:51)
at com.boeing.kmapi.base.skillset.service.impl.EssGenericReportServiceImpl.filterCommodityDetails(EssGenericReportServiceImpl.java:87)
at com.boeing.kmapi.base.skillset.service.impl.EssGenericReportServiceImpl.getGenericReport(EssGenericReportServiceImpl.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
The issue was resoled by adding projection to inner query.
commCriteria.createAlias("A1.b", "b1");
commCriteria.setProjection(Projections.projectionList().add(Projections.property("b1.c")));
The issue was resoled by adding projection to inner query.
commCriteria.createAlias("A1.b", "b1");
commCriteria.setProjection(Projections.projectionList().add(Projections.property("b1.c")));
It is a bug in Hibernate https://hibernate.atlassian.net/browse/HHH-993
As #Renjith said, it is solved by adding a projection to the DetachedCriteria.