List of usage examples for org.hibernate Session lock
void lock(Object object, LockMode lockMode);
From source file:org.grails.plugins.elasticsearch.index.IndexRequestQueue.java
License:Apache License
/** * Execute pending requests and clear both index & delete pending queues. * * @return Returns an OperationBatch instance which is a listener to the last executed bulk operation. Returns NULL * if there were no operations done on the method call. *//*from w w w. j av a 2s . co m*/ public OperationBatch executeRequests() { Map<IndexEntityKey, Object> toIndex = new LinkedHashMap<IndexEntityKey, Object>(); Set<IndexEntityKey> toDelete = new HashSet<IndexEntityKey>(); cleanOperationBatchList(); // Copy existing queue to ensure we are interfering with incoming requests. synchronized (this) { toIndex.putAll(indexRequests); toDelete.addAll(deleteRequests); indexRequests.clear(); deleteRequests.clear(); } // If there are domain instances that are both in the index requests & delete requests list, // they are directly deleted. toIndex.keySet().removeAll(toDelete); // If there is nothing in the queues, just stop here if (toIndex.isEmpty() && toDelete.isEmpty()) { return null; } BulkRequestBuilder bulkRequestBuilder = elasticSearchClient.prepareBulk(); //bulkRequestBuilder.setRefresh(true); // Execute index requests for (Map.Entry<IndexEntityKey, Object> entry : toIndex.entrySet()) { SearchableClassMapping scm = elasticSearchContextHolder .getMappingContextByType(entry.getKey().getClazz()); persistenceInterceptor.init(); try { Session session = SessionFactoryUtils.getSession(sessionFactory, true); Object entity = entry.getValue(); // If this not a transient instance, reattach it to the session if (session.contains(entity)) { session.lock(entity, LockMode.NONE); LOG.debug("Reattached entity to session"); } XContentBuilder json = toJSON(entity); bulkRequestBuilder.add(elasticSearchClient.prepareIndex().setIndex(scm.getIndexName()) .setType(scm.getElasticTypeName()).setId(entry.getKey().getId()) // TODO : Composite key ? .setSource(json)); if (LOG.isDebugEnabled()) { try { LOG.debug("Indexing " + entry.getKey().getClazz() + "(index:" + scm.getIndexName() + ",type:" + scm.getElasticTypeName() + ") of id " + entry.getKey().getId() + " and source " + json.string()); } catch (IOException e) { } } } finally { persistenceInterceptor.destroy(); } } // Execute delete requests for (IndexEntityKey key : toDelete) { SearchableClassMapping scm = elasticSearchContextHolder.getMappingContextByType(key.getClazz()); if (LOG.isDebugEnabled()) { LOG.debug("Deleting object from index " + scm.getIndexName() + " and type " + scm.getElasticTypeName() + " and ID " + key.getId()); } bulkRequestBuilder.add(elasticSearchClient.prepareDelete().setIndex(scm.getIndexName()) .setType(scm.getElasticTypeName()).setId(key.getId())); } // Perform bulk request OperationBatch completeListener = null; if (bulkRequestBuilder.numberOfActions() > 0) { completeListener = new OperationBatch(0, toIndex, toDelete); operationBatchList.add(completeListener); try { bulkRequestBuilder.execute().addListener(completeListener); } catch (Exception e) { throw new IndexException("Failed to index/delete " + bulkRequestBuilder.numberOfActions(), e); } } return completeListener; }
From source file:org.javamexico.dao.hib3.ForumDAO.java
License:Open Source License
public VotoForo vota(Usuario user, Foro foro, boolean up) throws PrivilegioInsuficienteException { if ((up && user.getReputacion() < minRepVotaFu) || (!up && user.getReputacion() < minRepVotaFd)) { throw new PrivilegioInsuficienteException( "El usuario no tiene privilegio suficiente para votar por un foro"); }/*from ww w . j a v a 2s . c o m*/ Session sess = sfact.getCurrentSession(); //Buscamos el voto a ver si ya se hizo VotoForo voto = findVoto(user, foro); int uprep = 0; if (voto == null) { //Si no existe lo creamos voto = new VotoForo(); voto.setFecha(new Date()); voto.setForo(foro); voto.setUp(up); voto.setUser(user); sess.save(voto); uprep = up ? 1 : -1; } else if (voto.isUp() != up) { //Si ya existe pero quieren cambio, se actualiza voto.setFecha(new Date()); voto.setUp(up); sess.update(voto); uprep = up ? 2 : -2; } if (uprep != 0) { sess.refresh(foro); //Esto no es nada intuitivo pero si no lo hago asi, se arroja una excepcion marciana de Hib user = (Usuario) sess.merge(foro.getAutor()); sess.lock(user, LockMode.UPGRADE); sess.refresh(user); user.setReputacion(user.getReputacion() + uprep); sess.update(user); sess.flush(); } return voto; }
From source file:org.javamexico.dao.hib3.ForumDAO.java
License:Open Source License
public VotoComentForo vota(Usuario user, ComentForo coment, boolean up) throws PrivilegioInsuficienteException { if ((up && user.getReputacion() < minRepVotaCu) || (!up && user.getReputacion() < minRepVotaCd)) { throw new PrivilegioInsuficienteException( "El usuario no tiene privilegio suficiente para votar por un comentario"); }/*from ww w .j av a2 s .c o m*/ Session sess = sfact.getCurrentSession(); VotoComentForo voto = findVoto(user, coment); int uprep = 0; if (voto == null) { voto = new VotoComentForo(); voto.setFecha(new Date()); voto.setComentario(coment); voto.setUp(up); voto.setUser(user); sess.save(voto); uprep = up ? 1 : -1; } else if (voto.isUp() != up) { voto.setUp(up); voto.setFecha(new Date()); sess.update(voto); uprep = up ? 2 : -2; } if (uprep != 0) { sess.refresh(coment); user = (Usuario) sess.merge(coment.getAutor()); sess.lock(user, LockMode.UPGRADE); sess.refresh(user); user.setReputacion(user.getReputacion() + uprep); sess.update(user); sess.flush(); } return voto; }
From source file:org.javamexico.dao.hib3.QuestionDAO.java
License:Open Source License
public VotoPregunta vota(Usuario user, Pregunta pregunta, boolean up) throws PrivilegioInsuficienteException { if ((up && user.getReputacion() < minRepVotaPu) || (!up && user.getReputacion() < minRepVotaPd)) { throw new PrivilegioInsuficienteException( "El usuario no tiene privilegio suficiente para votar por una pregunta"); }// w ww .j a va 2 s . co m Session sess = sfact.getCurrentSession(); VotoPregunta v = findVoto(user, pregunta); int updateRep = 0; if (v == null) { //Insertamos un nuevo voto v = new VotoPregunta(); v.setFecha(new Date()); v.setPregunta(pregunta); v.setUp(up); v.setUser(user); sess.save(v); updateRep = up ? 1 : -1; } else if (v.isUp() != up) { //Modificamos el voto existente v.setUp(up); v.setFecha(new Date()); sess.update(v); //Al cambiar voto, debe afectarse por 2 updateRep = up ? 2 : -2; } if (updateRep != 0) { //Actualizamos la reputacion del autor de la pregunta sess.refresh(pregunta); //Esto no es intuitivo pero si no lo hago asi, hib3 arroja excepcion marciana. user = (Usuario) sess.merge(pregunta.getAutor()); sess.lock(user, LockMode.UPGRADE); sess.refresh(user); user.setReputacion(user.getReputacion() + updateRep); sess.update(user); sess.flush(); } return v; }
From source file:org.javamexico.dao.hib3.QuestionDAO.java
License:Open Source License
public VotoRespuesta vota(Usuario user, Respuesta resp, boolean up) throws PrivilegioInsuficienteException { if ((up && user.getReputacion() < minRepVotaRu) || (!up && user.getReputacion() < minRepVotaRd)) { throw new PrivilegioInsuficienteException( "El usuario no tiene privilegio suficiente para votar por una respuesta"); }/*from www . j ava2 s . com*/ Session sess = sfact.getCurrentSession(); VotoRespuesta v = findVoto(user, resp); int updateRep = 0; if (v == null) { v = new VotoRespuesta(); v.setFecha(new Date()); v.setRespuesta(resp); v.setUp(up); v.setUser(user); sess.save(v); updateRep = up ? 1 : -1; } else if (v.isUp() != up) { v.setUp(up); v.setFecha(new Date()); sess.update(v); updateRep = up ? 2 : -2; } if (updateRep != 0) { sess.refresh(resp); user = (Usuario) sess.merge(resp.getAutor()); sess.lock(user, LockMode.UPGRADE); sess.refresh(user); user.setReputacion(user.getReputacion() + updateRep); sess.update(user); sess.flush(); } return v; }
From source file:org.jbpm.bpmn.flownodes.AbstractMergingGatewayActivity.java
License:Open Source License
/** * Joins the incoming executions.// w w w. j a v a 2 s . c om * Returns true if all executions have reached the gateway. */ protected boolean handleIncomingExecution(ExecutionImpl execution) { if (Execution.STATE_ACTIVE_CONCURRENT.equals(execution.getState())) { // force version increment in the parent execution Session session = EnvironmentImpl.getFromCurrent(Session.class); session.lock(execution.getParent(), lockMode); execution.setState(Execution.STATE_INACTIVE_JOIN); } execution.waitForSignal(); return isComplete(execution); }
From source file:org.jbpm.graph.node.Join.java
License:Open Source License
public void execute(ExecutionContext executionContext) { Token token = executionContext.getToken(); boolean isAbleToReactivateParent = token.isAbleToReactivateParent(); if (!token.hasEnded()) { token.end(false);//from w ww. j av a 2 s . co m } // if this token is not able to reactivate the parent, // we don't need to check anything if (isAbleToReactivateParent) { // the token arrived in the join and can only reactivate // the parent once token.setAbleToReactivateParent(false); Token parentToken = token.getParent(); if (parentToken != null) { JbpmContext jbpmContext = executionContext.getJbpmContext(); Session session = (jbpmContext != null ? jbpmContext.getSession() : null); if (session != null) { LockMode lockMode = LockMode.FORCE; if (parentLockMode != null) { lockMode = LockMode.parse(parentLockMode); } log.debug("forcing version increment on parent token " + parentToken); session.flush(); session.lock(parentToken, lockMode); } boolean reactivateParent = true; // if this is a discriminator if (isDiscriminator) { // reactivate the parent when the first token arrives in the // join. this must be the first token arriving because otherwise // the isAbleToReactivateParent() of this token should have been false // above. reactivateParent = true; // if a fixed set of tokenNames is specified at design time... } else if (tokenNames != null) { // check reactivation on the basis of those tokenNames reactivateParent = mustParentBeReactivated(parentToken, tokenNames.iterator()); // if a script is specified } else if (script != null) { // check if the script returns a collection or a boolean Object result = null; try { result = script.eval(token); } catch (Exception e) { this.raiseException(e, executionContext); } // if the result is a collection if (result instanceof Collection) { // it must be a collection of tokenNames Collection runtimeTokenNames = (Collection) result; reactivateParent = mustParentBeReactivated(parentToken, runtimeTokenNames.iterator()); // if it's a boolean... } else if (result instanceof Boolean) { // the boolean specifies if the parent needs to be reactivated reactivateParent = ((Boolean) result).booleanValue(); } // if a nOutOfM is specified } else if (nOutOfM != -1) { int n = 0; // wheck how many tokens already arrived in the join Iterator iter = parentToken.getChildren().values().iterator(); while (iter.hasNext()) { Token concurrentToken = (Token) iter.next(); if (this.equals(concurrentToken.getNode())) { n++; } } if (n < nOutOfM) { reactivateParent = false; } // if no configuration is specified.. } else { // the default behaviour is to check all concurrent tokens and reactivate // the parent if the last token arrives in the join reactivateParent = mustParentBeReactivated(parentToken, parentToken.getChildren().keySet().iterator()); } // if the parent token needs to be reactivated from this join node if (reactivateParent) { // write to all child tokens that the parent is already reactivated Iterator iter = parentToken.getChildren().values().iterator(); while (iter.hasNext()) { ((Token) iter.next()).setAbleToReactivateParent(false); } // write to all child tokens that the parent is already reactivated ExecutionContext parentContext = new ExecutionContext(parentToken); leave(parentContext); } } } }
From source file:org.jbpm.jpdl.internal.activity.JoinActivity.java
License:Open Source License
public void execute(ExecutionImpl execution) { Activity activity = execution.getActivity(); // if this is a single, non concurrent root if (Execution.STATE_ACTIVE_ROOT.equals(execution.getState())) { // just pass through Transition transition = activity.getDefaultOutgoingTransition(); if (transition == null) { throw new JbpmException("join must have an outgoing transition"); }//w w w. ja v a2 s . com execution.take(transition); } else if (Execution.STATE_ACTIVE_CONCURRENT.equals(execution.getState())) { // force version increment in the parent execution Session session = Environment.getFromCurrent(Session.class); session.lock(execution.getParent(), lockMode); execution.setState(Execution.STATE_INACTIVE_JOIN); execution.waitForSignal(); ExecutionImpl concurrentRoot = execution.getParent(); List<ExecutionImpl> joinedExecutions = getJoinedExecutions(concurrentRoot, activity); if (isComplete(joinedExecutions, activity)) { endJoinedExecutions(joinedExecutions); ExecutionImpl outgoingExecution = null; if (concurrentRoot.getExecutions().size() == 0) { outgoingExecution = concurrentRoot; outgoingExecution.setState(Execution.STATE_ACTIVE_ROOT); } else { outgoingExecution = concurrentRoot.createExecution(); outgoingExecution.setState(Execution.STATE_ACTIVE_CONCURRENT); } execution.setActivity(activity, outgoingExecution); Transition transition = activity.getDefaultOutgoingTransition(); if (transition == null) { throw new JbpmException("join must have an outgoing transition"); } outgoingExecution.take(transition); } } else { throw new JbpmException("invalid execution state"); } }
From source file:org.mifos.framework.util.helpers.TestObjectFactory.java
License:Open Source License
private static void deleteProductMix(final ProductMixBO prdmix) { Session session = StaticHibernateUtil.getSessionTL(); session.lock(prdmix, LockMode.UPGRADE); Transaction transaction = StaticHibernateUtil.startTransaction(); session.delete(prdmix);/*from w w w. j a v a2s . c o m*/ session.flush(); }
From source file:org.mifos.framework.util.helpers.TestObjectFactory.java
License:Open Source License
private static void deleteSavingProduct(final SavingsOfferingBO savingPrdBO) { Session session = StaticHibernateUtil.getSessionTL(); session.lock(savingPrdBO, LockMode.UPGRADE); Transaction transaction = StaticHibernateUtil.startTransaction(); session.delete(savingPrdBO);/* w ww .j ava 2 s. co m*/ session.flush(); }