List of usage examples for javax.persistence EntityTransaction rollback
public void rollback();
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Retrieves a specified quantity of annotations associated to a Resource specified by its URL and ordered by AnnotationStatus * @param _url/* w w w. j a va2s .c om*/ * @param asc * @param first_indice * @param max_results * @return */ public List<Annotation> retrieveAnnotationsGroupByStatus(String _url, boolean asc, int first_indice, int max_results) { //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url) .getSingleResult(); if (_uri == null) { tx.commit(); // //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : there is no uri " + _url); return new ArrayList<Annotation>(); } //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList(); String order_by_clause = " annotation.id desc"; if (asc) order_by_clause = " annotation.id asc"; Query _query = em.createQuery( "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.status," + order_by_clause) .setParameter(1, _uri); _query.setFirstResult(first_indice); _query.setMaxResults(max_results); List<Annotation> annotations = _query.getResultList(); //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList(); tx.commit(); //em.close(); return annotations; } catch (Exception e) { //tx.commit(); tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : " + e.getMessage()); return new ArrayList<Annotation>(); } }
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Retrieves a specified quantity of annotations associated to a specified Resource through its URL, ordered by FirstAuthor * @param _url/*from ww w . j a va 2s . co m*/ * @param asc * @param first_indice * @param max_results * @return */ public List<Annotation> retrieveAnnotationsGroupByFirstAuthor(String _url, boolean asc, int first_indice, int max_results) { //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url) .getSingleResult(); if (_uri == null) { tx.commit(); // //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : there is no uri " + _url); return new ArrayList<Annotation>(); } //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList(); String order_by_clause = " annotation.id desc"; if (asc) order_by_clause = " annotation.id asc"; Query _query = em.createQuery( "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.creator," + order_by_clause) .setParameter(1, _uri); _query.setFirstResult(first_indice); _query.setMaxResults(max_results); List<Annotation> annotations = _query.getResultList(); //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList(); tx.commit(); //em.close(); return annotations; } catch (Exception e) { //tx.commit(); tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations" + " cause : " + e.getMessage()); return new ArrayList<Annotation>(); } }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * {@inheritDoc}/* w w w . j a v a 2 s . co m*/ * * @see org.opencastproject.serviceregistry.api.ServiceRegistry#setMaintenanceStatus(java.lang.String, boolean) */ @Override public void setMaintenanceStatus(String baseUrl, boolean maintenance) throws NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); HostRegistrationJpaImpl reg = fetchHostRegistration(em, baseUrl); if (reg == null) { throw new NotFoundException("Can not set maintenance mode on a host that has not been registered"); } reg.setMaintenanceMode(maintenance); em.merge(reg); tx.commit(); hostsStatistics.updateHost(reg); } catch (RollbackException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { if (em != null) em.close(); } }
From source file:com.remediatetheflag.global.persistence.HibernatePersistenceFacade.java
public void updateExerciseInstanceUsedHints(ExerciseInstance ei, FlagQuestionHint hint) { EntityManager em = getHibernateEntityManager(); EntityTransaction et = em.getTransaction(); et.begin();/* w ww . j a va 2 s. c om*/ try { em.createNativeQuery("INSERT INTO exerciseInstances_flagQuestionHints " + "(ExerciseInstance_idExerciseInstance,usedHints_idFlagQuestionHint) " + "VALUES (?,?)") .setParameter(1, ei.getIdExerciseInstance()).setParameter(2, hint.getId()).executeUpdate(); et.commit(); em.close(); } catch (Exception e) { et.rollback(); em.close(); logger.error("Failed adding hint " + hint.getId() + " to exercise instance " + ei.getIdExerciseInstance() + " because of: \n" + e.getMessage()); } }
From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java
/** * Internal method to update the service registration state, throwing unwrapped JPA exceptions. * /*from w w w .j a v a2 s .c om*/ * @param em * the current entity manager * @param registration * the service registration to update * @return the updated service registration * @throws PersistenceException * if there is an exception thrown while persisting the job via JPA * @throws IllegalArgumentException */ private ServiceRegistration updateServiceState(EntityManager em, ServiceRegistrationJpaImpl registration) throws PersistenceException { EntityTransaction tx = em.getTransaction(); try { tx.begin(); ServiceRegistrationJpaImpl fromDb; fromDb = em.find(ServiceRegistrationJpaImpl.class, registration.getId()); if (fromDb == null) { throw new NoResultException(); } fromDb.setServiceState(registration.getServiceState()); fromDb.setStateChanged(registration.getStateChanged()); fromDb.setWarningStateTrigger(registration.getWarningStateTrigger()); fromDb.setErrorStateTrigger(registration.getErrorStateTrigger()); tx.commit(); servicesStatistics.updateService(registration); return registration; } catch (PersistenceException e) { if (tx.isActive()) { tx.rollback(); } throw e; } }
From source file:org.apache.juddi.config.AppConfig.java
private Properties getPersistentConfiguration(Configuration config) throws ConfigurationException { Properties result = new Properties(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//from w ww .jav a 2 s .co m boolean seedAlways = config.getBoolean("juddi.seed.always", false); if (seedAlways || !Install.alreadyInstalled(config)) { if (seedAlways) { log.info("Installing UDDI seed data, loading..."); } else { log.info("The 'root' publisher was not found, loading..."); } try { Install.install(config); } catch (Exception e) { throw new ConfigurationException(e); } catch (Throwable t) { throw new ConfigurationException(t); } } tx.begin(); String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); UddiEntityPublisher rootPublisher = new UddiEntityPublisher(rootPublisherStr); rootPublisher.populateKeyGeneratorKeys(em); List<String> rootKeyGenList = rootPublisher.getKeyGeneratorKeys(); if (rootKeyGenList == null || rootKeyGenList.size() == 0) throw new ConfigurationException( "The 'root' publisher key generator was not found. Please make sure that the application is properly installed."); String rootKeyGen = rootKeyGenList.iterator().next(); //rootKeyGen = rootKeyGen.substring((KeyGenerator.UDDI_SCHEME + KeyGenerator.PARTITION_SEPARATOR).length()); rootKeyGen = rootKeyGen.substring(0, rootKeyGen.length() - (KeyGenerator.PARTITION_SEPARATOR + KeyGenerator.KEYGENERATOR_SUFFIX).length()); log.debug("root partition: " + rootKeyGen); result.setProperty(Property.JUDDI_ROOT_PARTITION, rootKeyGen); // The node Id is defined as the business key of the business entity categorized as a node. This entity is saved as part of the install. // Only one business entity should be categorized as a node. String nodeId = ""; CategoryBag categoryBag = new CategoryBag(); KeyedReference keyedRef = new KeyedReference(); keyedRef.setTModelKey(Constants.NODE_CATEGORY_TMODEL); keyedRef.setKeyValue(Constants.NODE_KEYVALUE); categoryBag.getKeyedReference().add(keyedRef); List<?> keyList = FindBusinessByCategoryQuery.select(em, new FindQualifiers(), categoryBag, null); if (keyList != null && keyList.size() > 1) throw new ConfigurationException("Only one business entity can be categorized as the node."); if (keyList != null && keyList.size() > 0) { nodeId = (String) keyList.get(0); } else throw new ConfigurationException( "A node business entity was not found. Please make sure that the application is properly installed."); result.setProperty(Property.JUDDI_NODE_ID, nodeId); //result.setProperty(Property.JUDDI_NODE_ROOT_BUSINESS, nodeId); tx.commit(); return result; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java
/** * Processes the incoming request and calls the various methods to create * the right output stream./*from w w w .java 2 s . c om*/ * * @param request servlet request * @param response servlet response * * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); DataWrapper data = new DataWrapper(request, response); Object identity = null; EntityManager em; EntityTransaction tx = null; try { /* * Check IP lock */ checkRemoteIP(request); identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM); log.debug("Getting entity manager ......"); em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); tx = em.getTransaction(); tx.begin(); DataMonitoring rr = new DataMonitoring(); data.setRequestReporting(rr); String serviceName = OGCConstants.WMS_SERVICE_WMS; try { OGCScriptingRequest ogcrequest = calcOGCScriptingRequest(request); if (!ogcrequest.containsParameter(OGCScriptingRequest.COMMAND)) { throw new Exception("Bad request"); } data.setOgcrequest(ogcrequest); String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE); if (serviceParam != null || !"".equals(serviceParam)) { serviceName = serviceParam; } String iUrl = ogcrequest.getUrl(); String pcode = ogcrequest.getPersonalCode(); rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(), request.getMethod()); User user = checkLogin(request, em, pcode); if (ogcrequest != null) { ogcrequest.checkRequestURL(); } rr.setUserAndOrganization(user, user.getMainOrganization()); data.setHeader("X-Kaartenbalie-User", user.getUsername()); this.httpRequest = request; if (ogcrequest.getParameter(OGCScriptingRequest.COMMAND) .equalsIgnoreCase(OGCScriptingRequest.GET_GROUP_XML)) { GroupParser groupParser = new GroupParser(); groupParser.getGroupsAsXML(response, data.getOutputStream()); } else { parseRequestAndData(data, user); } } catch (AccessDeniedException adex) { log.error("Access denied: " + adex.getLocalizedMessage()); rr.setClientRequestException(adex); response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie"); } catch (Exception ex) { log.error("Error while handling request: ", ex); rr.setClientRequestException(ex); response.sendError(400, "Bad Request. See API documentation"); } finally { rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(), System.currentTimeMillis() - startTime); } tx.commit(); } catch (Exception ex) { log.error("Error creating EntityManager: ", ex); try { tx.rollback(); } catch (Exception ex2) { log.error("Error trying to rollback: ", ex2); } } finally { //log.debug("Closing entity manager ....."); MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM); } }
From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java
/** Processes the incoming request and calls the various methods to create the right output stream. * * @param request servlet request/* w w w . j a va2 s. com*/ * @param response servlet response * * @throws ServletException * @throws IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long startTime = System.currentTimeMillis(); StringBuffer baseUrl = createBaseUrl(request, true); if (CAPABILITIES_DTD == null) { CAPABILITIES_DTD = baseUrl.toString() + "/dtd/capabilities_1_1_1.dtd"; } if (EXCEPTION_DTD == null) { EXCEPTION_DTD = baseUrl.toString() + "/dtd/exception_1_1_1.dtd"; } if (DESCRIBELAYER_DTD == null) { DESCRIBELAYER_DTD = baseUrl.toString() + "/dtd/WMS_DescribeLayerResponse.dtd"; } DataWrapper data = new DataWrapper(request, response); Object identity = null; EntityManager em; EntityTransaction tx = null; try { identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM); em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); tx = em.getTransaction(); tx.begin(); DataMonitoring rr = new DataMonitoring(); data.setRequestReporting(rr); String serviceName = OGCConstants.WMS_SERVICE_WMS; try { OGCRequest ogcrequest = calcOGCRequest(request); String personalCode = null; if (ogcrequest != null) personalCode = ogcrequest.getPersonalCode(); data.setOgcrequest(ogcrequest); String serviceParam = ogcrequest.getParameter(OGCConstants.SERVICE); if (serviceParam != null || !"".equals(serviceParam)) { serviceName = serviceParam; } String iUrl = ogcrequest.getUrl(); rr.startClientRequest(iUrl, iUrl.getBytes().length, startTime, request.getRemoteAddr(), request.getMethod()); User user = checkLogin(request, personalCode, em); ogcrequest.checkRequestURL(); Organization mainOrg = null; String userName = null; if (user != null) { mainOrg = user.getMainOrganization(); userName = user.getUsername(); } rr.setUserAndOrganization(user, mainOrg); data.setHeader("X-Kaartenbalie-User", userName); parseRequestAndData(data, user); } catch (AccessDeniedException adex) { rr.setClientRequestException(adex); response.addHeader("WWW-Authenticate", "Basic realm=\"Kaartenbalie login\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access denied to Kaartenbalie"); } catch (ProviderException pex) { log.error("Error while communicating with provider: " + pex.getLocalizedMessage()); rr.setClientRequestException(pex); handleRequestException(pex, data); } catch (Exception e) { log.error(String.format("Error while handling request for URI %s, query string %s: %s: %s", request.getRequestURI(), request.getQueryString(), e.getClass().getName(), e.getMessage()), e); rr.setClientRequestException(e); handleRequestException(e, data); } finally { rr.endClientRequest(serviceName, data.getOperation(), data.getContentLength(), System.currentTimeMillis() - startTime); } if (!tx.getRollbackOnly()) { tx.commit(); } } catch (Exception ex) { log.error("Error creating EntityManager", ex); handleRequestException(ex, data); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
public void setPublisherAssertions(String authInfo, Holder<List<PublisherAssertion>> publisherAssertion) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*from ww w . j a va2 s . c o m*/ tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion); List<?> businessKeysFound = null; businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound); // First, wipe out all previous assertions associated with this publisher DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound); // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new"). List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = publisherAssertion.value; for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) { org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion(); MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion); org.apache.juddi.model.BusinessEntity beFrom = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey()); org.apache.juddi.model.BusinessEntity beTo = em.find(org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey()); modelPubAssertion.setBusinessEntityByFromKey(beFrom); modelPubAssertion.setBusinessEntityByToKey(beTo); modelPubAssertion.setFromCheck("false"); modelPubAssertion.setToCheck("false"); em.persist(modelPubAssertion); if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey())) modelPubAssertion.setFromCheck("true"); if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey())) modelPubAssertion.setToCheck("true"); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime); } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:fr.natoine.dao.annotation.DAOAnnotation.java
/** * Tests if an agent has expressed an opinion (agree or disagree) on a resource * @param _creator/*from www. ja va 2s . com*/ * @param _url_to_test * @return */ public boolean agreementExpressed(Agent _creator, String _url_to_test) { long nb = 0; //EntityManagerFactory emf = this.setEMF(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url_to_test) .getSingleResult(); if (_uri == null) { tx.commit(); System.out.println("[RetrieveAnnotation.agreementExpressed] unable to retrieve Annotations" + " cause : there is no uri " + _url_to_test); return false; } AnnotationStatus status_agree = (AnnotationStatus) em .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Accord") .getSingleResult(); AnnotationStatus status_disagree = (AnnotationStatus) em .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Dsaccord") .getSingleResult(); AnnotationStatus status_clarify = (AnnotationStatus) em .createQuery("from AnnotationStatus where label = ?").setParameter(1, "A clarifier") .getSingleResult(); //if(status_agree != null) if (status_agree != null || status_disagree != null || status_clarify != null) { Object nb_annotations_agree = em.createQuery( " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? and annotation.creator=? and (annotation.status=? or annotation.status=? or annotation.status=?)") .setParameter(1, _uri).setParameter(2, _creator).setParameter(3, status_agree) .setParameter(4, status_disagree).setParameter(5, status_clarify).getSingleResult(); if (nb_annotations_agree instanceof Long) { nb = ((Long) nb_annotations_agree).longValue(); } } tx.commit(); if (nb > 0) return true; else return false; } catch (Exception e) { tx.rollback(); //em.close(); System.out.println("[RetrieveAnnotation.agreementExpressed] unable to retrieve Annotations" + " on url : " + _url_to_test + " cause : " + e.getMessage()); return false; //to prevent to express its opinion if the system fails } }