List of usage examples for javax.persistence EntityTransaction rollback
public void rollback();
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
/** Create on POST. * E.g. curl -d '{...}' http://localhost:8888/author/configuration/ * @param req/*from w w w . j a va 2 s. c o m*/ * @param resp * @throws ServletException * @throws IOException */ private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub try { Object o = parseObject(req); if (filterByCreator) { String creator = getRequestCreator(req); setCreator(o, creator); } Key key = validateCreate(o); // try adding EntityManager em = EMF.get().createEntityManager(); EntityTransaction et = em.getTransaction(); try { et.begin(); if (em.find(getObjectClass(), key) != null) throw new RequestException(HttpServletResponse.SC_CONFLICT, "object already exists (" + key + ")"); em.persist(o); et.commit(); logger.info("Added " + o); } finally { if (et.isActive()) et.rollback(); em.close(); } resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); listObject(jw, o); w.close(); } catch (RequestException e) { resp.sendError(e.getErrorCode(), e.getMessage()); } catch (Exception e) { logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } }
From source file:com.eucalyptus.images.Images.java
public static ImageInfo createPendingFromDeviceMapping(UserFullName creator, String imageNameArg, String imageDescription, ImageMetadata.Architecture requestArch, ImageMetadata.Platform imagePlatform, final List<BlockDeviceMappingItemType> blockDeviceMappings) throws Exception { final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix()); BlockStorageImageInfo ret = new BlockStorageImageInfo(creator, imageId, imageNameArg, imageDescription, new Long(-1), requestArch, imagePlatform, null, null, "snap-EUCARESERVED", false, Images.DEFAULT_ROOT_DEVICE); /// device with snap-EUCARESERVED is the placeholder to indicate register is for create-image only /// actual root device with snapshot is filled in later BlockDeviceMappingItemType toRemove = null; for (final BlockDeviceMappingItemType device : blockDeviceMappings) { if (Images.findCreateImageRoot().apply(device)) toRemove = device;//from w w w . ja v a2 s .c o m } if (toRemove != null) blockDeviceMappings.remove(toRemove); final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class); try { ret = Entities.merge(ret); ret.setState(ImageMetadata.State.pending); ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString()); ret.getDeviceMappings() .addAll(Lists.transform(blockDeviceMappings, Images.deviceMappingGenerator(ret, -1))); tx.commit(); LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + creator); } catch (Exception e) { tx.rollback(); throw new EucalyptusCloudException( "Failed to register pending bfebs image because of: " + e.getMessage(), e); } finally { if (tx.isActive()) tx.rollback(); } return ret; }
From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java
@Override public void updateEventWithMetadata(long eventId, Properties caProperties) throws SchedulerServiceDatabaseException, NotFoundException { if (caProperties == null) { caProperties = new Properties(); }/*from www . j a v a 2 s .c o m*/ String caSerialized; try { caSerialized = serializeProperties(caProperties); } catch (IOException e) { logger.error("Could not serialize properties: {}", e); throw new SchedulerServiceDatabaseException(e); } EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); EventEntity entity = em.find(EventEntity.class, eventId); if (entity == null) { throw new NotFoundException("Event with ID: " + eventId + " does not exist"); } entity.setCaptureAgentMetadata(caSerialized); em.merge(entity); tx.commit(); } catch (NotFoundException e) { logger.error("Event with ID '{}' does not exist", eventId); throw e; } catch (Exception e) { if (tx.isActive()) { tx.rollback(); } logger.error("Could not store event metadata: {}", e.getMessage()); throw new SchedulerServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:com.google.inject.persist.jpa.KuneJpaLocalTxnInterceptor.java
/** * Returns True if rollback DID NOT HAPPEN (i.e. if commit should continue). * /*from w ww . j a v a2 s . com*/ * @param transactional * The metadata annotaiton of the method * @param e * The exception to test for rollback * @param txn * A JPA Transaction to issue rollbacks on * @return true, if successful */ private boolean rollbackIfNecessary(final KuneTransactional transactional, final Exception e, final EntityTransaction txn) { boolean commit = true; // check rollback clauses for (final Class<? extends Exception> rollBackOn : transactional.rollbackOn()) { // if one matched, try to perform a rollback if (rollBackOn.isInstance(e)) { commit = false; // check ignore clauses (supercedes rollback clause) for (final Class<? extends Exception> exceptOn : transactional.ignore()) { // An exception to the rollback clause was found, DON'T rollback // (i.e. commit and throw anyway) if (exceptOn.isInstance(e)) { commit = true; break; } } // rollback only if nothing matched the ignore check if (!commit) { txn.rollback(); } // otherwise continue to commit break; } } return commit; }
From source file:de.peterspan.csv2db.converter.Converter.java
@Override protected Void doInBackground() throws Exception { EntityTransaction tx = null; try {/*from ww w . j a v a 2 s . c o m*/ tx = entityManager.getTransaction(); tx.begin(); List<String[]> allLines = readFile(); double increment = 100.0 / allLines.size(); double progress = 0.0; for (String[] line : allLines) { progress = progress + increment; setProgress((int) Math.round(progress)); if (line[0].equals("locnumber")) { //This is the header! Create a single instance header object Header.getInstance().init(line); continue; } if (line[0].equals("")) { continue; } readLine(line); } entityManager.flush(); tx.commit(); } catch (HibernateException he) { log.error("An error occured. Tx will be rolledback!", he); if (tx != null) { tx.rollback(); } } return null; }
From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java
@Override public void deleteComment(String eventId, long commentId) throws NotFoundException, EventCommentDatabaseException { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*from w w w .j a v a 2s .com*/ tx.begin(); EventCommentDto event = getEventComment(eventId, commentId, em); if (event == null) throw new NotFoundException( "Event comment with ID " + eventId + " and " + commentId + " does not exist"); em.remove(event); tx.commit(); sendMessageUpdate(eventId); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete event comment: {}", ExceptionUtils.getStackTrace(e)); if (tx.isActive()) tx.rollback(); throw new EventCommentDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:de.zib.gndms.logic.model.TaskAction.java
/** * Invokes a rollback on an entity transaction and a following {@code begin()}, * only if it has been marked (using {@code setRollbackOnly()}). * * @param txParam a transaction to be rewinded *//* ww w .j a va 2 s.co m*/ private void rewindTransaction(final EntityTransaction txParam) { if (txParam.isActive()) { if (txParam.getRollbackOnly()) { txParam.rollback(); txParam.begin(); } } else txParam.begin(); }
From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java
/** * Register a new application./*from ww w .ja va 2 s . c o m*/ * * @param application The application to register * @return The registered application */ @POST @Status(Response.Status.CREATED) @Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE }) @Produces(Constants.INDIGOMIMETYPE) public final Application createApplication(final Application application) { if (application.getInfrastructureIds() == null || application.getInfrastructureIds().isEmpty()) { throw new BadRequestException(); } Date now = new Date(); application.setDateCreated(now); EntityManager em = getEntityManager(); EntityTransaction et = null; try { et = em.getTransaction(); et.begin(); List<Infrastructure> lstInfra = new LinkedList<>(); for (String infraId : application.getInfrastructureIds()) { Infrastructure infra = em.find(Infrastructure.class, infraId); if (infra == null) { throw new BadRequestException(); } lstInfra.add(infra); } application.setInfrastructures(lstInfra); em.persist(application); et.commit(); log.debug("New application registered: " + application.getId()); } catch (BadRequestException re) { throw re; } catch (RuntimeException re) { log.error("Impossible to create the application"); log.error(re); throw re; } finally { if (et != null && et.isActive()) { et.rollback(); } em.close(); } return application; }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
public void rollback() { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }/*from w w w . ja va 2 s. c o m*/ // commit transaction EntityTransaction transaction = entityManager.getTransaction(); if (transaction.isActive()) { transaction.rollback(); } }
From source file:org.apache.juddi.v3.auth.JUDDIAuthenticator.java
/** * @return the userId that came in on the request providing the user has * a publishing account in jUDDI./*from w w w . j a v a 2 s . co m*/ * @param authorizedName * @param credential * @return authorizedName * @throws AuthenticationException */ public String authenticate(String authorizedName, String credential) throws AuthenticationException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!"); int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try { MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; log.error("config exception! " + authorizedName, ex); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(authorizedName); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } return authorizedName; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }