Java Examples for javax.persistence.PersistenceException

The following java examples will help you to understand the usage of javax.persistence.PersistenceException. These source code samples are taken from different open source projects.

Example 1
Project: goos-code-examples-master  File: JPATransactor.java View source code
public void perform(UnitOfWork unitOfWork) throws Exception {
    final EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
        unitOfWork.work();
        transaction.commit();
    } catch (PersistenceException e) {
        throw e;
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}
Example 2
Project: pyramus-master  File: UserVariableDAO.java View source code
public String findByUserAndKey(User user, String key) {
    UserVariableKeyDAO variableKeyDAO = DAOFactory.getInstance().getUserVariableKeyDAO();
    UserVariableKey userVariableKey = variableKeyDAO.findByVariableKey(key);
    if (userVariableKey != null) {
        UserVariable userVariable = findByUserAndVariableKey(user, userVariableKey);
        return userVariable == null ? null : userVariable.getValue();
    } else {
        throw new PersistenceException("Unknown VariableKey");
    }
}
Example 3
Project: ebean-master  File: TestBeanStateReset.java View source code
@Test
public void resetForInsert() {
    // setup to fail foreign key constraint
    MnyC c = new MnyC();
    c.setId(Long.MAX_VALUE);
    MnyB b = new MnyB();
    b.getCs().add(c);
    try {
        // inserts of b succeeds but intersection insert fails FK check on c
        b.save();
    } catch (PersistenceException e) {
        logger.info("expected error " + e.getMessage());
        Ebean.getBeanState(b).resetForInsert();
        b.getCs().clear();
        LoggedSqlCollector.start();
        b.setName("mod");
        b.save();
        List<String> sql = LoggedSqlCollector.stop();
        assertThat(sql.get(0)).contains("insert into mny_b (id, name, version, when_created, when_modified, a_id) values (");
    }
}
Example 4
Project: ef-orm-master  File: Case2.java View source code
/**
	 * 测试多数æ?®æº?下,命å??查询å?¯ä»¥æŒ‡å®šæ•°æ?®æº?
	 * @throws SQLException
	 */
@Test(expected = PersistenceException.class)
public void testDataSourceBind() throws SQLException {
    //Person对象所在的数��为DataSource2		
    //由于�置中指定默认数��为datasource2,因此�以正常查出
    List<Person> persons = db.createNamedQuery("getUserById", Person.class).setParameter("name", "张三").getResultList();
    System.out.println(persons);
    //这个�置未指定绑定的数��,因此会抛出异常
    try {
        List<Person> p2 = db.createNamedQuery("getUserById-not-bind-ds", Person.class).setParameter("name", "张三").getResultList();
    } catch (RuntimeException e) {
        throw e;
    }
}
Example 5
Project: playflow-master  File: ExceptionMapper.java View source code
public static Result toResult(RuntimeException re) {
    Logger.error("ERROR: ", re);
    String msg = re.getMessage();
    if (msg == null) {
        // api doesn't allow null strings
        msg = "";
    }
    re.printStackTrace();
    if (re instanceof NotFoundException) {
        return Results.notFound(msg);
    } else if (re instanceof ForbiddenException) {
        return Results.forbidden(msg);
    } else if (re instanceof IllegalStateException || re instanceof IllegalArgumentException || re instanceof UnsupportedOperationException || re instanceof PersistenceException) {
        return Results.badRequest(re.getMessage());
    }
    return Results.internalServerError(msg);
}
Example 6
Project: Trivial4b-master  File: Jpa.java View source code
public static EntityManager createEntityManager() {
    EntityManager entityManager = null;
    try {
        entityManager = getEmf().createEntityManager();
        emThread.set(entityManager);
    } catch (javax.persistence.PersistenceException e) {
        System.err.println("¡ ERROR - Seguramente NO se han añadido las dos librerias de la carpeta 'lib' (Donde se encuentra hibernate3.), al Build Path del proyecto.  !");
        System.exit(0);
    }
    return entityManager;
}
Example 7
Project: yeslib-master  File: YesJpaTemplate.java View source code
public int bulkUpdateNamedQuery(final String queryName, final Object... values) throws DataAccessException {
    return (Integer) execute(new JpaCallback() {

        @Override
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query queryObject = em.createNamedQuery(queryName);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.executeUpdate();
        }
    });
}
Example 8
Project: compose-idm-master  File: AbstractListEntityService.java View source code
public final Object listAllEntities(Event event) throws IdManagementException {
    try {
        verifyACListAllEntities(event);
        Object res = postACListAllEntities(event);
        LOG.info(event.getLoggingDetails());
        return res;
    } catch (IdManagementException e) {
        throw e;
    } catch (PersistenceException ex) {
        throw new IdManagementException("An error ocurred while listing all the entities", ex, LOG, "A persistenceException occurred while listing all the entities: " + event.getLoggingDetails(), Level.ERROR, 500);
    } catch (Exception ex) {
        throw new IdManagementException("An error ocurred while listing all the entities", ex, LOG, "An unexpected exception occurred while listing all the entities: " + event.getLoggingDetails(), Level.ERROR, 500);
    }
}
Example 9
Project: org.nabucco.framework.base-master  File: PersistenceExceptionMapper.java View source code
/**
     * Maps all sub-classes of <code>javax.persistence.PersistenceException</code> to
     * <code>org.nabucco.framework.base.facade.exception.PersistenceException</code>:
     * <p>
     * EntityExistsException, EntityNotFoundException, NonUniqueResultException, NoResultException,
     * OptimisticLockException, RollbackException, TransactionRequiredException
     * 
     * @param exception
     *            the input exception
     * 
     * @return the according NABUCCO exception
     */
public static PersistenceException resolve(Exception exception) {
    PersistenceException out = null;
    StringBuilder resultMessage = new StringBuilder();
    resultMessage.append("Error during persistence operation: ");
    resultMessage.append(exception.getMessage());
    if (exception instanceof PersistenceException) {
        return (PersistenceException) exception;
    } else if (exception instanceof javax.persistence.EntityExistsException) {
        out = new EntityExistsException(resultMessage.toString());
    } else if (exception instanceof javax.persistence.EntityNotFoundException) {
        out = new EntityNotFoundException(resultMessage.toString());
    } else if (exception instanceof javax.persistence.NonUniqueResultException) {
        out = new NonUniqueResultException(resultMessage.toString());
    } else if (exception instanceof javax.persistence.NoResultException) {
        out = new EntityNotFoundException(resultMessage.toString());
    } else if (exception instanceof javax.persistence.OptimisticLockException) {
        out = new OptimisticLockException(resultMessage.toString());
    } else if (exception instanceof javax.persistence.RollbackException) {
        out = new PersistenceException(resultMessage.toString(), exception);
    } else if (exception instanceof javax.persistence.TransactionRequiredException) {
        out = new PersistenceException(resultMessage.toString(), exception);
    } else {
        out = new PersistenceException(resultMessage.toString(), exception);
    }
    return out;
}
Example 10
Project: compass-fork-master  File: AbstractEntityManagerWrapper.java View source code
public void close() throws JpaGpsDeviceException, PersistenceException {
    try {
        commitTransaction();
    } finally {
        if (shouldCloseEntityManager()) {
            try {
                entityManager.close();
            } catch (PersistenceException e) {
                log.warn("Failed to close JPA EntityManager", e);
            } finally {
                entityManager = null;
            }
        }
    }
}
Example 11
Project: debop4j-master  File: JPAStandaloneNoOGMTest.java View source code
@Test
public void jtaStandaloneNoOgm() throws Exception {
    // Failure is expected as we did't configure a JDBC connection nor a Dialect
    // (and this would fail only if effectively lading Hibernate OGM without OGM superpowers)
    error.expect(javax.persistence.PersistenceException.class);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone-noogm");
    // should not be reached, but cleanup in case the test fails.
    emf.close();
}
Example 12
Project: dropwizard-master  File: PersistenceExceptionMapper.java View source code
@Override
public Response toResponse(PersistenceException e) {
    LOGGER.error("Hibernate error", e);
    Throwable t = e.getCause();
    // PersistenceException wraps the real exception, so we look for the real exception mapper for it
    // Cast is necessary since the return type is ExceptionMapper<? extends Throwable> and Java
    // does not allow calling toResponse on the method with a Throwable
    @SuppressWarnings("unchecked") final ExceptionMapper<Throwable> exceptionMapper = (ExceptionMapper<Throwable>) providers.getExceptionMapper(t.getClass());
    return exceptionMapper.toResponse(t);
}
Example 13
Project: hibernate-orm-master  File: ImmutableEntityNaturalIdTest.java View source code
@Test
public void testNaturalIdCheck() throws Exception {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Parent p = new Parent("alex");
    Child c = new Child("billy", p);
    s.persist(p);
    s.persist(c);
    t.commit();
    s.close();
    Field name = c.getClass().getDeclaredField("name");
    name.setAccessible(true);
    name.set(c, "phil");
    s = openSession();
    t = s.beginTransaction();
    try {
        s.saveOrUpdate(c);
        s.flush();
        fail("should have failed because immutable natural ID was altered");
    } catch (PersistenceException e) {
    } finally {
        t.rollback();
        s.close();
    }
    name.set(c, "billy");
    s = openSession();
    t = s.beginTransaction();
    s.delete(c);
    s.delete(p);
    t.commit();
    s.close();
}
Example 14
Project: Hibernate-Search-on-action-master  File: EntityManagerInvocationHandler.java View source code
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    FullTextEntityManager entityManager = Search.getFullTextEntityManager(factory.createEntityManager());
    EntityManagerHolder.setFullTextEntityManager(entityManager);
    EntityTransaction tx = null;
    Object result;
    try {
        tx = entityManager.getTransaction();
        tx.begin();
        result = method.invoke(delegate, args);
        tx.commit();
    } catch (PersistenceException e) {
        rollbackIfNeeded(tx);
        throw e;
    } catch (SearchException e) {
        rollbackIfNeeded(tx);
        throw e;
    } finally {
        entityManager.close();
        EntityManagerHolder.setFullTextEntityManager(null);
    }
    return result;
}
Example 15
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: BookingService.java View source code
@SuppressWarnings("unchecked")
@Transactional
public List<Hotel> findHotels(final String searchPattern, final int firstResult, final int maxResults) {
    logger.debug("Looking for a Hotel.");
    return getJpaTemplate().executeFind(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            return em.createQuery("select h from Hotel h where lower(h.name) like :search or lower(h.city) like :search or lower(h.zip) like :search or lower(h.address) like :search").setParameter("search", searchPattern).setMaxResults(maxResults).setFirstResult(firstResult).getResultList();
        }
    });
}
Example 16
Project: mobicents-master  File: AuthenticatorAction.java View source code
public boolean authenticate() {
    try {
        currentUser = (User) entityManager.createQuery("select u from User u where u.userName = #{identity.username} and u.password = #{identity.password}").getSingleResult();
    } catch (PersistenceException e) {
        return false;
    }
    actor.setId(identity.getUsername());
    if (currentUser instanceof Admin) {
        actor.getGroupActorIds().add("shippers");
        actor.getGroupActorIds().add("reviewers");
        identity.addRole("admin");
    }
    return true;
}
Example 17
Project: poireauxvinaigrette-master  File: Cuisiner.java View source code
public static Result cuisine(String msisdn, String to, String messageId, String text, String type) {
    Menu sms = new Menu();
    try {
        sms.resto = Resto.find.where().eq("mobile", msisdn).findUnique();
        if (sms.resto == null) {
            return internalServerError(msisdn + " mobile inconnu");
        }
        sms.destinataire = to;
        sms.messageId = messageId;
        sms.text = text;
        sms.typeMsg = type;
        sms.creationDate = new Date();
        String messagetimestamp = request().getQueryString("message-timestamp");
        sms.receptionDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(messagetimestamp);
        Ebean.save(sms);
    } catch (Exception e) {
        String message;
        if (e instanceof PersistenceException)
            message = e.getCause().getMessage();
        else
            message = e.getMessage();
        return internalServerError("Oops :  " + message);
    }
    return ok("Sms received :" + sms.messageId);
}
Example 18
Project: saos-master  File: DefaultIsolationLevelJpaDialect.java View source code
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
    if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        log.warn("changing isolation level to ISOLATION_DEFAULT, jpa does not handle custom isolation levels");
    }
    DefaultTransactionDefinition def = new DefaultTransactionDefinition(definition);
    def.setIsolationLevelName("ISOLATION_DEFAULT");
    return super.beginTransaction(entityManager, def);
}
Example 19
Project: seam-2.2-master  File: BookingService.java View source code
@SuppressWarnings("unchecked")
@Transactional
public List<Hotel> findHotels(final String searchPattern, final int firstResult, final int maxResults) {
    logger.debug("Looking for a Hotel.");
    return getJpaTemplate().executeFind(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            return em.createQuery("select h from Hotel h where lower(h.name) like :search or lower(h.city) like :search or lower(h.zip) like :search or lower(h.address) like :search").setParameter("search", searchPattern).setMaxResults(maxResults).setFirstResult(firstResult).getResultList();
        }
    });
}
Example 20
Project: seam2jsf2-master  File: BookingService.java View source code
@SuppressWarnings("unchecked")
@Transactional
public List<Hotel> findHotels(final String searchPattern, final int firstResult, final int maxResults) {
    logger.debug("Looking for a Hotel.");
    return getJpaTemplate().executeFind(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            return em.createQuery("select h from Hotel h where lower(h.name) like :search or lower(h.city) like :search or lower(h.zip) like :search or lower(h.address) like :search").setParameter("search", searchPattern).setMaxResults(maxResults).setFirstResult(firstResult).getResultList();
        }
    });
}
Example 21
Project: web-framework-master  File: PersistenceExceptionMapper.java View source code
@Override
public Response toResponse(PersistenceException e) {
    LOGGER.error("Hibernate error", e);
    Throwable t = e.getCause();
    // PersistenceException wraps the real exception, so we look for the real exception mapper for it
    // Cast is necessary since the return type is ExceptionMapper<? extends Throwable> and Java
    // does not allow calling toResponse on the method with a Throwable
    @SuppressWarnings("unchecked") final ExceptionMapper<Throwable> exceptionMapper = (ExceptionMapper<Throwable>) providers.getExceptionMapper(t.getClass());
    return exceptionMapper.toResponse(t);
}
Example 22
Project: school-master  File: LearningServiceTest.java View source code
@Test
public void shouldRollbackChangesDueToDatabaseError() throws Exception {
    KlassService fakeKlassService = mock(KlassService.class);
    when(fakeKlassService.create(any())).thenThrow(new javax.persistence.PersistenceException());
    this.learningService.setKlassService(fakeKlassService);
    Date date = Date.valueOf("2015-11-03");
    List<String> emails = Arrays.asList("bobaabb", "saraaabb", "joeaabb", "samaabb");
    Teacher teacher = new Teacher("frank", 33, Gender.MALE);
    Klass klass = new Klass("chemistry", date, 4, Department.SCIENCE, 300);
    try {
        klass = this.learningService.enroll(emails, teacher, klass);
    } catch (PersistenceException e) {
    }
    Student student1 = this.studentService.findByEmail("aaa@aol.com");
    Student student2 = this.studentService.findByEmail("sam");
    assertNotNull(student1);
    assertNull(student2);
}
Example 23
Project: ameba-master  File: JsonProcessingExceptionMapper.java View source code
/**
     * {@inheritDoc}
     */
@Override
public Response toResponse(JsonProcessingException exception) {
    Throwable throwable = exception;
    while (throwable != null) {
        if (throwable instanceof PersistenceException) {
            return exceptionMappers.get().findMapping(throwable).toResponse(throwable);
        }
        throwable = throwable.getCause();
    }
    logger.debug("Json Processing error", exception);
    String message = exception.getOriginalMessage();
    String desc = null;
    String source = null;
    if (mode.isDev()) {
        desc = IOUtils.getStackTrace(exception);
        JsonLocation location = exception.getLocation();
        if (location != null) {
            source = "line: " + location.getLineNr() + ", column: " + location.getColumnNr();
        } else {
            source = exception.getStackTrace()[0].toString();
        }
    }
    ErrorMessage errorMessage = ErrorMessage.fromStatus(Response.Status.BAD_REQUEST.getStatusCode());
    errorMessage.setThrowable(exception);
    errorMessage.setCode(Hashing.murmur3_32().hashUnencodedChars(exception.getClass().getName()).toString());
    errorMessage.addError(new Result.Error(errorMessage.getCode(), message != null ? message : exception.getMessage(), desc, source));
    return Response.status(errorMessage.getStatus()).entity(errorMessage).type(ExceptionMapperUtils.getResponseType()).build();
}
Example 24
Project: androidrocks-master  File: JpaDAO.java View source code
@SuppressWarnings("unchecked")
public List<E> findAll() {
    Object res = getJpaTemplate().execute(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createQuery("SELECT h FROM " + entityClass.getName() + " h");
            return q.getResultList();
        }
    });
    return (List<E>) res;
}
Example 25
Project: apis-master  File: OpenJPAExceptionTranslator.java View source code
@Override
public Exception translate(Throwable e) {
    if (e.getCause() != null && isRelevantCause(e.getCause())) {
        return translate(e.getCause());
    }
    Class<? extends Throwable> c = e.getClass();
    if (c.equals(org.apache.openjpa.persistence.EntityExistsException.class)) {
        return new javax.persistence.EntityExistsException(e.getMessage(), e);
    } else if (c.equals(javax.validation.ConstraintViolationException.class)) {
        return (Exception) e;
    }
    LOG.info("Cannot translate '{}' to specific subtype, will return generic PersistenceException", e.getClass().getName());
    return new PersistenceException(e);
}
Example 26
Project: arpnet-standard-master  File: QueryStatisticFinder.java View source code
/**
     * Only returns Lists at this stage.
     */
public BeanCollection<MetaQueryPlanStatistic> findMany(BeanQueryRequest<MetaQueryPlanStatistic> request) {
    SpiQuery.Type queryType = ((SpiQuery<?>) request.getQuery()).getType();
    if (!queryType.equals(SpiQuery.Type.LIST)) {
        throw new PersistenceException("Only findList() supported at this stage.");
    }
    BeanList<MetaQueryPlanStatistic> list = new BeanList<MetaQueryPlanStatistic>();
    SpiEbeanServer server = (SpiEbeanServer) request.getEbeanServer();
    build(list, server);
    String orderBy = request.getQuery().order().toStringFormat();
    if (orderBy == null) {
        orderBy = "beanType, origQueryPlanHash, autofetchTuned";
    }
    server.sort(list, orderBy);
    return list;
}
Example 27
Project: axelor-business-suite-master  File: PartnerBaseRepository.java View source code
@Override
public Partner save(Partner partner) {
    try {
        if (partner.getPartnerSeq() == null) {
            String seq = Beans.get(SequenceService.class).getSequenceNumber(IAdministration.PARTNER);
            if (seq == null)
                throw new AxelorException(I18n.get(IExceptionMessage.PARTNER_1), IException.CONFIGURATION_ERROR);
            partner.setPartnerSeq(seq);
        }
        return super.save(partner);
    } catch (Exception e) {
        throw new PersistenceException(e.getLocalizedMessage());
    }
}
Example 28
Project: BatooJPA-master  File: PessimisticLockTest.java View source code
/**
	 * Tests the optimistic lock.
	 * 
	 * @since 2.0.0
	 */
@Test(expected = PersistenceException.class)
public void testPessimisticLockUpdate() {
    final Foo2 foo = this.newFoo(false);
    this.persist(foo);
    this.commit();
    final EntityManager em2 = this.emf().createEntityManager();
    try {
        final Foo2 foo2 = em2.find(Foo2.class, foo.getId());
        final EntityTransaction tx2 = em2.getTransaction();
        tx2.begin();
        foo2.setValue("test2");
        tx2.commit();
        this.begin();
        foo.setValue("test3");
        this.commit();
    } finally {
        em2.close();
    }
}
Example 29
Project: BeanTest-master  File: TestPersistenceExceptionPropagation.java View source code
@Test(expected = PersistenceException.class)
public void shouldCauseExceptionBecuaseUniquenessViolation() {
    MyEJBService myEJBService = getBean(MyEJBService.class);
    MyEntityWithConstraints entity = new MyEntityWithConstraints("123");
    myEJBService.save(entity);
    entity = new MyEntityWithConstraints("123");
    myEJBService.save(entity);
    fail("Should have failed because uniqueness violation");
}
Example 30
Project: deprecated-avaje-ebeanorm-api-master  File: EbeanServerFactory.java View source code
/**
   * Create using the ServerConfig object to configure the server.
   */
public static EbeanServer create(ServerConfig config) {
    if (config.getName() == null) {
        throw new PersistenceException("The name is null (it is required)");
    }
    EbeanServer server = serverFactory.createServer(config);
    if (config.isDefaultServer()) {
        GlobalProperties.setSkipPrimaryServer(true);
    }
    if (config.isRegister()) {
        Ebean.register(server, config.isDefaultServer());
    }
    return server;
}
Example 31
Project: devicehive-java-server-master  File: WebSocketResponseBuilder.java View source code
public JsonObject buildResponse(JsonObject request, WebSocketSession session) {
    JsonObject response;
    try {
        response = requestProcessor.process(request, session).getResponseAsJson();
    } catch (BadCredentialsException ex) {
        logger.error("Unauthorized access", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Invalid credentials").build();
    } catch (AccessDeniedException ex) {
        logger.error("Access to action is denied", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized").build();
    } catch (HiveException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createError(ex).build();
    } catch (ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()).build();
    } catch (org.hibernate.exception.ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
    } catch (JsonParseException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, Messages.INVALID_REQUEST_PARAMETERS).build();
    } catch (OptimisticLockException ex) {
        logger.error("Error executing the request", ex);
        logger.error("Data conflict", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, Messages.CONFLICT_MESSAGE).build();
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
        } else {
            response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()).build();
        }
    } catch (Exception ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()).build();
    }
    return new JsonMessageBuilder().addAction(request.get(JsonMessageBuilder.ACTION)).addRequestId(request.get(JsonMessageBuilder.REQUEST_ID)).include(response).build();
}
Example 32
Project: easyjweb-master  File: ClientSimpleDAOImpl.java View source code
public Object doInJpa(EntityManager entitymanager) throws PersistenceException {
    StringBuffer sql = new StringBuffer("select obj from Client obj ");
    if (StringUtils.hasLength(scope)) {
        sql.append(" where ").append(scope);
    }
    Query query = entitymanager.createQuery(sql.toString());
    if (params != null) {
        for (int i = 0; i < params.length; i++) query.setParameter(i + 1, params[i]);
    }
    if (begin > 0) {
        query.setFirstResult(begin);
        query.setMaxResults(max);
    }
    return query.getResultList();
}
Example 33
Project: fluxtream-app-master  File: UpdateFailedException.java View source code
public boolean isPermanent() {
    final Throwable cause = getCause();
    if (cause != null) {
        // typical internal errors that will consistently crash the udpate
        String className = cause.getClass().toString();
        boolean serverException = false;
        if (cause instanceof PersistenceException) {
            serverException = true;
        }
        if (className.startsWith("org.springframework"))
            serverException = true;
        else if (className.startsWith("java.lang.NullPointerException"))
            serverException = true;
        if (serverException) {
            StringBuffer sb = new StringBuffer();
            if (reason != null)
                sb.append(reason).append(ApiKey.PermanentFailReason.DIVIDER).append(className);
            else
                sb.append(ApiKey.PermanentFailReason.SERVER_EXCEPTION).append(ApiKey.PermanentFailReason.DIVIDER).append(className);
            this.reason = sb.toString();
            return true;
        }
    }
    return isPermanent;
}
Example 34
Project: gisgraphy-master  File: LanguageDao.java View source code
public Object doInHibernate(Session session) throws PersistenceException {
    String queryString = "from " + Language.class.getSimpleName() + " as l where Iso639Alpha2LanguageCode= ?";
    Query qry = session.createQuery(queryString);
    qry.setCacheable(true);
    qry.setParameter(0, iso639Alpha2LanguageCode.toUpperCase());
    Language result = (Language) qry.uniqueResult();
    return result;
}
Example 35
Project: gisgraphy-mirror-master  File: IntersectsRestrictionTest.java View source code
public Object doInHibernate(Session session) throws PersistenceException {
    Criteria testCriteria = session.createCriteria(OpenStreetMap.class);
    List<String> fieldList = new ArrayList<String>();
    fieldList.add("name");
    fieldList.add("gid");
    Projection projection = ProjectionBean.fieldList(fieldList, true);
    testCriteria.setProjection(projection).add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME, GeolocHelper.createPolygonBox(6.94130445F, 50.91544865F, 10000))).setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class));
    List<_OpenstreetmapDTO> results = testCriteria.list();
    return results;
}
Example 36
Project: GT-FHIR-master  File: BaseFhirDao.java View source code
public BaseResourceEntity updateEntity(final IResource theResource, BaseResourceEntity entity, boolean theUpdateHistory, Date theDeletedTimestampOrNull, boolean thePerformIndexing, boolean theUpdateVersion) {
    entity.constructEntityFromResource(theResource);
    try {
        if (entity.getId() == null) {
            myEntityManager.persist(entity);
        } else {
            entity = myEntityManager.merge(entity);
        }
        myEntityManager.flush();
        if (theResource != null) {
            theResource.setId(new IdDt(entity.getId()));
        }
    } catch (PersistenceException e) {
        Throwable cause = e.getCause();
        String message = null;
        while (cause != null) {
            message = cause.getMessage();
            cause = cause.getCause();
        }
        if (message.contains("denied") || message.contains("forbidden")) {
            throw new ForbiddenOperationException("This operation is not allowed for the current user on the selected server.");
        } else {
            throw new InternalErrorException(message);
        }
    }
    return entity;
}
Example 37
Project: hibernate-ogm-master  File: DuplicateIdDetectionTest.java View source code
@Test
public void cannotInsertSameEntityTwice() throws Exception {
    em.getTransaction().begin();
    // given
    MakeupArtist wibke = new MakeupArtist("wibke", "halloween");
    em.persist(wibke);
    em.getTransaction().commit();
    em.clear();
    em.getTransaction().begin();
    // when
    MakeupArtist notWibke = new MakeupArtist("wibke", "glamorous");
    em.persist(notWibke);
    try {
        em.getTransaction().commit();
        fail("Expected exception wasn't raised");
    } catch (Exception e) {
        assertThat(e.getCause()).isExactlyInstanceOf(PersistenceException.class);
        assertThat(e.getCause().getMessage()).matches(".*OGM000067.*");
    }
    em.clear();
    em.getTransaction().begin();
    MakeupArtist loadedMakeupArtist = em.find(MakeupArtist.class, "wibke");
    assertThat(loadedMakeupArtist).isNotNull();
    assertThat(loadedMakeupArtist.getFavoriteStyle()).describedAs("Second insert should not be applied").isEqualTo("halloween");
    em.remove(loadedMakeupArtist);
    em.getTransaction().commit();
}
Example 38
Project: hibhik-master  File: CustomPersistence.java View source code
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
    EntityManagerFactory emf = null;
    List<PersistenceProvider> providers = getProviders();
    PersistenceProvider defaultProvider = null;
    for (PersistenceProvider provider : providers) {
        if (provider instanceof HibernatePersistence) {
            defaultProvider = provider;
            continue;
        }
        emf = provider.createEntityManagerFactory(persistenceUnitName, properties);
        if (emf != null) {
            break;
        }
    }
    if (emf == null && defaultProvider != null)
        emf = defaultProvider.createEntityManagerFactory(persistenceUnitName, properties);
    if (emf == null) {
        throw new PersistenceException("No Persistence provider for EntityManager named " + persistenceUnitName);
    }
    return emf;
}
Example 39
Project: Kundera-master  File: ReflectUtils.java View source code
/**
	 * Loads class with className using classLoader.
	 * 
	 * @param className
	 *            the class name
	 * @param classLoader
	 *            the class loader
	 * @return the class
	 */
public static Class<?> classForName(String className, ClassLoader classLoader) {
    try {
        Class<?> c = null;
        try {
            c = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            try {
                c = Class.forName(className);
            } catch (ClassNotFoundException e1) {
                if (classLoader == null) {
                    throw e1;
                } else {
                    c = classLoader.loadClass(className);
                }
            }
        }
        return c;
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    }
}
Example 40
Project: OpenMEAP-master  File: GlobalSettingsAddModifyNotifier.java View source code
@Override
public <E extends Event<GlobalSettings>> void onBeforeOperation(E event, List<ProcessingEvent> events) throws EventNotificationException {
    GlobalSettings settings = (GlobalSettings) event.getPayload();
    if (settings == null || settings.getId() == null || !settings.getId().equals(Long.valueOf(1))) {
        throw new PersistenceException("There can be only 1 instance of GlobalSettings.  " + "Please first acquire with modelManager.getGlobalSettings(), make modifications, then update.");
    }
}
Example 41
Project: play-logger-master  File: ExceptionsMonitoringPlugin.java View source code
public static void register(String source, Throwable e) {
    if (e instanceof ActionNotFoundException)
        return;
    if (e instanceof UnexpectedException || e instanceof InvocationTargetException || e instanceof JavaExecutionException || e instanceof PersistenceException) {
        if (e.getCause() != null)
            e = e.getCause();
    }
    String key = "[" + source + "] " + key(e);
    AtomicInteger value = exceptions.get(key);
    if (value == null)
        exceptions.put(key, value = new AtomicInteger());
    value.incrementAndGet();
}
Example 42
Project: sculptor-master  File: JpaSaveAccessImpl.java View source code
@Override
public void performExecute() throws PersistenceException {
    if (entity != null) {
        result = performMerge(entity);
    }
    if (entities != null) {
        List<T> newInstances = new ArrayList<T>();
        for (T each : getEntities()) {
            newInstances.add(performMerge(each));
        }
        setEntities(newInstances);
    }
}
Example 43
Project: service-framework-master  File: JPAContext.java View source code
public void closeTx(boolean rollback) {
    try {
        if (entityManager.getTransaction().isActive()) {
            if (rollback || entityManager.getTransaction().getRollbackOnly()) {
                entityManager.getTransaction().rollback();
            } else {
                try {
                    entityManager.getTransaction().commit();
                } catch (Throwable e) {
                    for (int i = 0; i < 10; i++) {
                        if (e instanceof PersistenceException && e.getCause() != null) {
                            e = e.getCause();
                            break;
                        }
                        e = e.getCause();
                        if (e == null) {
                            break;
                        }
                    }
                    throw new RuntimeException("Cannot commit", e);
                }
            }
        }
    } finally {
        entityManager.close();
        //clear context
        jpaConfig.clearJPAContext();
    }
}
Example 44
Project: STARDOM-master  File: HibernateExtendedJpaDialect.java View source code
/**
     * This method is overridden to set custom isolation levels on the connection
     * @param entityManager
     * @param definition
     * @return
     * @throws PersistenceException
     * @throws SQLException
     * @throws TransactionException
     */
@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }
    entityManager.getTransaction().begin();
    logger.debug("Transaction started");
    session.doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            logger.debug("The connection instance is {}", connection);
            logger.debug("The isolation level of the connection is {} and the isolation level set on the transaction is {}", connection.getTransactionIsolation(), definition.getIsolationLevel());
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
        }
    });
    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}
Example 45
Project: Struts2-Rest-Jpa-BootStap-master  File: WorkgroupServices.java View source code
public Workgroup load(final Short id) {
    if (LOG.isDebugEnabled())
        LOG.debug("load");
    Workgroup workgroup;
    try {
        EntityManagerHelper.beginTransaction();
        JpaWorkgroupDAO workgroupDAO = new JpaWorkgroupDAO();
        workgroup = workgroupDAO.findById(id);
        EntityManagerHelper.commitAndCloseEntityManager();
    } catch (PersistenceException ex) {
        LOG.error("Error", ex);
        throw ex;
    } finally {
        if (EntityManagerHelper.isCloseEntityManager() == false)
            EntityManagerHelper.rollback();
    }
    return workgroup;
}
Example 46
Project: tapestry-model-master  File: QueryParameter.java View source code
/**
	 * Apply the parameters to the given Query object.
	 *
	 * @param queryObject the Query object
	 *          if thrown by the Query object
	 */
public void applyNamedParameterToQuery(Query queryObject) throws PersistenceException {
    /* TODO
		if (value instanceof Collection)

		{
			if (type != null)
			{
				queryObject.setParameterList(name, (Collection) value, type);
			} else
			{
				queryObject.setParameterList(name, (Collection) value);
			}
		} else if (value instanceof Object[])
		{
			if (type != null)
			{
				queryObject.setParameterList(name, (Object[]) value, type);
			} else
			{
				queryObject.setParameterList(name, (Object[]) value);
			}
		} else
		{
		 */
    if (type != null) {
        queryObject.setParameter(new Parameter() {

            public String getName() {
                return name;
            }

            public Integer getPosition() {
                return null;
            }

            public Class getParameterType() {
                //To change body of implemented methods use File | Settings | File Templates.
                return null;
            }
        }, type);
    } else {
        queryObject.setParameter(name, value);
    }
//}
}
Example 47
Project: titanic-javaee7-master  File: ProgramacionRepositorio.java View source code
@Transaccion
public void removerProgramacion(Programacion programacion) {
    try {
        programacion = obtenerProgramacion(programacion.getIdeProgramacion());
        entityManager.remove(programacion);
        entityManager.flush();
    } catch (PersistenceException e) {
        throw new NegocioExcepciones("La programación no puede ser eliminada.");
    }
}
Example 48
Project: xtext-master  File: JpaSaveAccessImpl.java View source code
@Override
public void performExecute() throws PersistenceException {
    if (entity != null) {
        result = performMerge(entity);
    }
    if (entities != null) {
        List<T> newInstances = new ArrayList<T>();
        for (T each : getEntities()) {
            newInstances.add(performMerge(each));
        }
        setEntities(newInstances);
    }
}
Example 49
Project: Raildelays-master  File: SkipUniqueKeyViolationPolicy.java View source code
private static boolean isExpectedViolation(Throwable e) {
    boolean violated = false;
    if (e instanceof ConstraintViolationException) {
        // We must ignore accent (we use Local.ENGLISH for that) and case
        violated = matchAnyViolationNames(((ConstraintViolationException) e).getConstraintName().toUpperCase(Locale.ENGLISH)::equals);
    } else if (e instanceof SQLIntegrityConstraintViolationException) {
        // We must ignore accent (we use Local.ENGLISH for that) and case
        violated = matchAnyViolationNames(e.getMessage().toUpperCase(Locale.ENGLISH)::contains);
    } else if (e instanceof PersistenceException && e.getCause() != null || e instanceof DataIntegrityViolationException) {
        /**
             * We are in the case where Hibernate encapsulate the Exception into a PersistenceException.
             * Then we must check recursively into causes.
             */
        violated = isExpectedViolation(e.getCause());
    }
    return violated;
}
Example 50
Project: spring-framework-2.5.x-master  File: PersistenceExceptionTranslationAdvisorTests.java View source code
private void doTestTranslationNeededForTheseExceptions(RepositoryInterfaceImpl target) {
    RepositoryInterface ri = createProxy(target);
    target.setBehavior(persistenceException1);
    try {
        ri.noThrowsClause();
        fail();
    } catch (DataAccessException ex) {
        assertSame(persistenceException1, ex.getCause());
    } catch (PersistenceException ex) {
        fail("Should have been translated");
    }
    try {
        ri.throwsPersistenceException();
        fail();
    } catch (PersistenceException ex) {
        assertSame(persistenceException1, ex);
    }
}
Example 51
Project: spring-framework-master  File: EntityManagerFactoryUtilsTests.java View source code
/*
	 * Test method for
	 * 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessException(PersistenceException)'
	 */
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
    EntityNotFoundException entityNotFound = new EntityNotFoundException();
    assertSame(JpaObjectRetrievalFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
    NoResultException noResult = new NoResultException();
    assertSame(EmptyResultDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
    NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
    assertSame(IncorrectResultSizeDataAccessException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
    OptimisticLockException optimisticLock = new OptimisticLockException();
    assertSame(JpaOptimisticLockingFailureException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
    EntityExistsException entityExists = new EntityExistsException("foo");
    assertSame(DataIntegrityViolationException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
    TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
    assertSame(InvalidDataAccessApiUsageException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
    PersistenceException unknown = new PersistenceException() {
    };
    assertSame(JpaSystemException.class, EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
Example 52
Project: abiquo-master  File: BusinessDelegateProxy.java View source code
/**
     * Intercepts all calls to business logic and checks user session.
     * 
     * @param target The target object to invoke.
     * @param method The target method to invoke.
     * @param args The arguments of the method.
     * @throws Throwable If an exception is thrown on the target method.
     * @see BasicCommand#execute(UserSession, String[], Object[], Class)
     */
@Override
public Object invoke(final Object target, final Method method, final Object[] args) throws Exception, Throwable {
    // Check database connectivity
    if (!HibernateDAOFactory.instance().pingDB()) {
        throw new PersistenceException("Could not connect to the database. " + "Please contact the cloud administrator.");
    }
    // Check if the user session is valid and if the user have permissions
    // to execute the target method
    AuthService.getInstance().checkUserPermissions(userSession, method.getName());
    try {
        return method.invoke(delegate, args);
    } catch (InvocationTargetException ex) {
        throw ex.getTargetException();
    }
}
Example 53
Project: beacon-of-beacons-master  File: OrganizationDaoImpl.java View source code
@Override
public Organization findByName(String name) {
    if (name == null) {
        throw new NullPointerException("name");
    }
    Organization o = null;
    try {
        o = em.createNamedQuery("findOrganizationByName", Organization.class).setParameter("name", name).getSingleResult();
    } catch (PersistenceException ex) {
        o = null;
    }
    return o;
}
Example 54
Project: Capturador-master  File: EJBErrorAndExceptionHandler.java View source code
@AroundInvoke
public Object handleErrorOrException(InvocationContext invocationContext) throws Exception {
    Class clas = invocationContext.getTarget().getClass();
    Method method = invocationContext.getMethod();
    // following lines belong to the logger class
    Logger theLogger = Logger.getLogger(EJBErrorAndExceptionHandler.class.getName());
    theLogger.addHandler(new FileHandler("aralog.xml"));
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (int index = 0; index < handlers.length; index++) {
        handlers[index].setLevel(Level.FINE);
    }
    theLogger.setLevel(Level.FINE);
    try {
        return invocationContext.proceed();
    } catch (SQLGrammarException ex) {
        JSFMessage.addErrorMessage("not_yet");
        if ("searchByCriteria".equals(method.getName())) {
            return null;
        } else if ("countSpecimensByCriteria".equals(method.getName())) {
            return new Long(0);
        } else {
            return null;
        }
    } catch (TransactionRolledbackException ex) {
        JSFMessage.addErrorMessage("not_yet");
        if ("searchByCriteria".equals(method.getName())) {
            return null;
        } else if ("countSpecimensByCriteria".equals(method.getName())) {
            return new Long(0);
        } else {
            return null;
        }
    } catch (PersistenceException ex) {
        JSFMessage.addErrorMessage("not_yet");
        if ("searchByCriteria".equals(method.getName())) {
            return null;
        } else if ("countSpecimensByCriteria".equals(method.getName())) {
            return new Long(0);
        } else {
            return null;
        }
    } catch (Exception ex) {
        String s = ex.getLocalizedMessage();
        String cl = ex.getClass().getName();
        theLogger.fine(clas.getName());
        theLogger.fine(method.getName());
        JSFMessage.addErrorMessage("not_yet");
        if ("searchByCriteria".equals(method.getName())) {
            return null;
        } else if ("countSpecimensByCriteria".equals(method.getName())) {
            return new Long(0);
        } else {
            return null;
        }
    }
}
Example 55
Project: cloudtm-data-platform-master  File: JPAStandaloneNoOGMTest.java View source code
@Test
public void testJTAStandaloneNoOgm() throws Exception {
    // Failure is expected as we didn't configure a JDBC connection nor a Dialect
    // (and this would fail only if effectively loading Hibernate ORM without OGM superpowers)
    error.expect(javax.persistence.PersistenceException.class);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone-noogm");
    // should not be reached, but cleanup in case the test fails.
    emf.close();
}
Example 56
Project: cnery-master  File: CNeryEntityHome.java View source code
@Override
public String update() {
    try {
        return super.update();
    } catch (ConstraintViolationException cve) {
        statusMessages.clear();
        for (ConstraintViolation<?> cv : cve.getConstraintViolations()) {
            statusMessages.add((ConstraintViolation<Object>) cv);
        }
        clearFactoryInstance();
    } catch (PersistenceException pe) {
        Throwable t = pe.getCause();
        if (t == null)
            t = pe;
        statusMessages.clear();
        statusMessages.add(t.getLocalizedMessage());
        clearFactoryInstance();
    }
    return null;
}
Example 57
Project: ddd-leaven-v2-master  File: HibernateExtendedJpaDialect.java View source code
/**
     * This method is overridden to set custom isolation levels on the connection
     * @param entityManager
     * @param definition
     * @return
     * @throws PersistenceException
     * @throws SQLException
     * @throws TransactionException
     */
@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }
    entityManager.getTransaction().begin();
    logger.debug("Transaction started");
    session.doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            logger.debug("The connection instance is {}", connection);
            logger.debug("The isolation level of the connection is {} and the isolation level set on the transaction is {}", connection.getTransactionIsolation(), definition.getIsolationLevel());
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
        }
    });
    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}
Example 58
Project: eclipselink.runtime-master  File: TestSessionCustomizer.java View source code
@Test
public void invalidInstance() {
    props.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, new Object());
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(PU_NAME, props);
    try {
        emf.createEntityManager();
        Assert.fail();
    } catch (PersistenceException e) {
        Assert.assertTrue(e.toString(), e.getCause() instanceof ClassCastException);
    } finally {
        if (emf != null) {
            emf.close();
        }
    }
}
Example 59
Project: google-guice-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 60
Project: guice-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 61
Project: jadira-master  File: HibernateEntityManagerFactoryBean.java View source code
@Override
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
    if (this.transactionManager != null) {
        configurationTransactionManagerHolder.set(this.transactionManager);
    }
    try {
        return super.createNativeEntityManagerFactory();
    } finally {
        if (this.transactionManager != null) {
            configurationTransactionManagerHolder.set(null);
        }
    }
}
Example 62
Project: libmythtv-java-master  File: DbUtils.java View source code
public static EntityManagerFactory createEntityManagerFactory(SchemaVersion version, String host, int port, String database, String user, String password) throws DatabaseException {
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    Properties props = new Properties();
    props.put(PROP_URL, "jdbc:mysql://" + host + ":" + port + "/" + database + "?zeroDateTimeBehavior=convertToNull");
    props.put(PROP_USER, user);
    props.put(PROP_PASSWORD, password);
    try {
        LOGGER.trace("Attempting to connect using schema version {}", version);
        final EntityManagerFactory factory = Persistence.createEntityManagerFactory(version.getPersistenceUnitName(), props);
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                if (factory.isOpen()) {
                    factory.close();
                }
            }
        });
        return factory;
    } catch (PersistenceException e) {
        throw new DatabaseException("Unable to access \"" + database + "\" at " + host + ":" + port, e);
    }
}
Example 63
Project: logging-log4j2-master  File: ContextStackJsonAttributeConverter.java View source code
@Override
public String convertToDatabaseColumn(final ThreadContext.ContextStack contextStack) {
    if (contextStack == null) {
        return null;
    }
    try {
        return ContextMapJsonAttributeConverter.OBJECT_MAPPER.writeValueAsString(contextStack.asList());
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert stack list to JSON string.", e);
    }
}
Example 64
Project: Moogle-Muice-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 65
Project: palava-jpa-master  File: TransactionFilter.java View source code
@Override
public Map<String, Object> filter(IpcCall call, IpcCommand command, IpcCallFilterChain chain) throws IpcCommandExecutionException {
    final EntityManager manager = provider.get();
    final EntityTransaction tx = manager.getTransaction();
    LOG.debug("Starting transaction");
    tx.begin();
    final Map<String, Object> result;
    try {
        result = chain.filter(call, command);
    /*CHECKSTYLE:OFF*/
    } catch (RuntimeException e) {
        LOG.error("Execution failed, rolling back", e);
        tx.rollback();
        throw e;
    } catch (IpcCommandExecutionException e) {
        LOG.error("Filtering failed, rolling back", e);
        tx.rollback();
        throw e;
    }
    try {
        assert tx.isActive() : "Transaction should be active";
        tx.commit();
        LOG.debug("Commit succeeded");
        return result;
    } catch (PersistenceException e) {
        LOG.error("Commit failed, rolling back", e);
        tx.rollback();
        throw e;
    }
}
Example 66
Project: play2-crud-master  File: CachedDAO.java View source code
public void remove(K key) throws EntityNotFoundException {
    listeners.beforeRemove(key);
    M ref = find.ref(key);
    if (ref == null)
        throw new EntityNotFoundException(key);
    try {
        ref.delete();
    } catch (PersistenceException e) {
        throw new EntityNotFoundException(key, e);
    }
    find.clean(key);
    listeners.afterRemove(key, ref);
}
Example 67
Project: roboguice-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 68
Project: schotel-master  File: CityDaoImpl.java View source code
@Override
public List<City> getCityHotelGreaterThan100() {
    List<City> cities = null;
    try {
        //select o from City o where o.openApiId in (select h.cityId from HotelInfo h group by h.cityId having count(h) > 100)
        cities = getEm().createQuery("select o from City o where o.openApiId in (select h.cityId from HotelInfo h group by h.cityId having count(h) > 100)").getResultList();
    } catch (PersistenceException e) {
        logger.error(e.getMessage());
    }
    return cities;
}
Example 69
Project: sisu-guice-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 70
Project: SlipStreamServer-master  File: VmTest.java View source code
@Test
public void cloudInstanceIdUserMustBeUnique() throws Exception {
    boolean exceptionOccured = false;
    boolean firstInsertAccepted = false;
    EntityManager em = PersistenceUtil.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        String sqlInsert1 = String.format("INSERT INTO Vm (ID, CLOUD, INSTANCEID, STATE, USER_) VALUES (10, 'lokal', 'instance100', 'up', '%s');", user.getName());
        String sqlInsert2 = String.format("INSERT INTO Vm (ID, CLOUD, INSTANCEID, STATE, USER_) VALUES (10, 'lokal', 'instance100', 'down', '%s');", user.getName());
        Query query1 = em.createNativeQuery(sqlInsert1);
        Query query2 = em.createNativeQuery(sqlInsert2);
        int res = query1.executeUpdate();
        assertEquals(1, res);
        firstInsertAccepted = true;
        res = query2.executeUpdate();
        transaction.commit();
    } catch (PersistenceException pe) {
        exceptionOccured = true;
        transaction.rollback();
        boolean isCorrectException = pe.getCause().getCause().getClass() == SQLIntegrityConstraintViolationException.class;
        assertTrue("The cause of the cause sould be SQLIntegrityConstraintViolationException.", isCorrectException);
    }
    assertTrue("First insert should have worked", firstInsertAccepted);
    assertTrue("Second insert should have failed", exceptionOccured);
}
Example 71
Project: tita-master  File: TitaLoginContext.java View source code
/**
     * {@inheritDoc}
     */
@Override
public Subject getSubject(String username, String password) throws LoginException {
    if (username != null) {
        DefaultSubject user = new DefaultSubject();
        try {
            TiTAUser u = service.getUserByUsername(username);
            if (TiTASecurity.calcHash(password).equals(u.getPassword())) {
                if (u.getRole().getDescription().toLowerCase().equals("administrator")) {
                    user.addPrincipal(new SimplePrincipal("admin"));
                    TitaSession.getSession().setRole("admin");
                } else if (u.getRole().getDescription().toLowerCase().equals("time controller")) {
                    user.addPrincipal(new SimplePrincipal("timecontroller"));
                    TitaSession.getSession().setRole("timecontroller");
                } else if (u.getRole().getDescription().toLowerCase().equals("time consumer")) {
                    user.addPrincipal(new SimplePrincipal("timeconsumer"));
                    TitaSession.getSession().setRole("timeconsumer");
                    if (u.getTitaUserProjects().size() <= 0) {
                        throw new LoginException("Login of user " + username + " was correct. But the " + username + " is not assign to a open project. " + "Please contact the administartor!");
                    }
                } else {
                    throw new LoginException("Login of user " + username + " failed.");
                }
            } else {
                throw new LoginException("Login of user " + username + " failed.");
            }
        } catch (PersistenceException e) {
            throw new LoginException("Login of user " + username + " failed.");
        } catch (NoSuchAlgorithmException e) {
            log.error("Hash Algorithm not found!");
        }
        return user;
    }
    throw new LoginException("Login of user " + username + " failed.");
}
Example 72
Project: VaadinUtils-master  File: SingleEntityWizardStep.java View source code
/**
	 * commits the container and retrieves the new recordid
	 *
	 * we have to hook the ItemSetChangeListener to be able to get the database
	 * id of a new record.
	 */
private E commitContainerAndGetEntityFromDB() {
    // don't really need an AtomicReference, just using it as a mutable
    // final variable to be used in the callback
    final AtomicReference<E> newEntity = new AtomicReference<>();
    // call back to collect the id of the new record when the container
    // fires the ItemSetChangeEvent
    ItemSetChangeListener tmp = new ItemSetChangeListener() {

        /**
			 *
			 */
        private static final long serialVersionUID = 9132090066374531277L;

        @Override
        public void containerItemSetChange(ItemSetChangeEvent event) {
            if (event instanceof ProviderChangedEvent) {
                @SuppressWarnings("rawtypes") ProviderChangedEvent pce = (ProviderChangedEvent) event;
                @SuppressWarnings("unchecked") Collection<E> affectedEntities = pce.getChangeEvent().getAffectedEntities();
                if (affectedEntities.size() > 0) {
                    @SuppressWarnings("unchecked") E id = (E) affectedEntities.toArray()[0];
                    newEntity.set(id);
                }
            }
        }
    };
    try {
        // add the listener
        container.addItemSetChangeListener(tmp);
        // call commit
        container.commit();
        newEntity.set(EntityManagerProvider.getEntityManager().merge(newEntity.get()));
    } catch (com.vaadin.data.Buffered.SourceException e) {
        if (e.getCause() instanceof javax.persistence.PersistenceException) {
            javax.persistence.PersistenceException cause = (javax.persistence.PersistenceException) e.getCause();
            Notification.show(cause.getCause().getMessage(), Type.ERROR_MESSAGE);
        }
    } finally {
        // detach the listener
        container.removeItemSetChangeListener(tmp);
    }
    // return the entity
    return newEntity.get();
}
Example 73
Project: activiti-engine-5.12-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 74
Project: activiti-engine-ppi-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 75
Project: Activiti-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 76
Project: appverse-web-master  File: QueryJpaCallback.java View source code
public int countInJpa(EntityManager em) throws PersistenceException {
    // create query
    if (query == null) {
        query = em.createQuery(queryString);
    }
    // set parameters
    if (namedParameters != null) {
        for (QueryJpaCallbackParameter namedParameter : namedParameters) {
            query.setParameter(namedParameter.getName(), namedParameter.getValue());
        }
    } else if (indexedParameters != null) {
        for (int i = 0; i < indexedParameters.length; i++) {
            query.setParameter(i + 1, indexedParameters[i]);
        }
    }
    int total = ((Long) query.getSingleResult()).intValue();
    return total;
}
Example 77
Project: aries-master  File: XATxContextBindingEntityManager.java View source code
@Override
protected final EntityManager getRealEntityManager() {
    TransactionContext txContext = txControl.getCurrentContext();
    if (txContext == null) {
        throw new TransactionException("The resource " + provider + " cannot be accessed outside of an active Transaction Context");
    }
    EntityManager existing = (EntityManager) txContext.getScopedValue(resourceId);
    if (existing != null) {
        return existing;
    }
    TransactionControl previous = commonTxStore.get();
    commonTxStore.set(txControl);
    EntityManager toReturn;
    EntityManager toClose;
    try {
        if (txContext.getTransactionStatus() == NO_TRANSACTION) {
            toClose = provider.createEntityManager();
            toReturn = new ScopedEntityManagerWrapper(toClose);
        } else if (txContext.supportsXA()) {
            toClose = provider.createEntityManager();
            toReturn = new TxEntityManagerWrapper(toClose);
            toClose.joinTransaction();
        } else {
            throw new TransactionException("There is a transaction active, but it does not support local participants");
        }
    } catch (Exception sqle) {
        commonTxStore.set(previous);
        throw new TransactionException("There was a problem getting hold of a database connection", sqle);
    }
    txContext.postCompletion( x -> {
        try {
            toClose.close();
        } catch (PersistenceException sqle) {
        }
        commonTxStore.set(previous);
    });
    txContext.putScopedValue(resourceId, toReturn);
    return toReturn;
}
Example 78
Project: atlas-lb-master  File: DeleteConnectionThrottleListener.java View source code
@Override
public void doOnMessage(final Message message) throws Exception {
    LOG.debug("Entering " + getClass());
    LOG.debug(message);
    LoadBalancer queueLb = getLoadbalancerFromMessage(message);
    LoadBalancer dbLoadBalancer;
    try {
        dbLoadBalancer = loadBalancerService.get(queueLb.getId(), queueLb.getAccountId());
    } catch (EntityNotFoundException enfe) {
        String alertDescription = String.format("Load balancer '%d' not found in database.", queueLb.getId());
        LOG.error(alertDescription, enfe);
        notificationService.saveAlert(queueLb.getAccountId(), queueLb.getId(), enfe, DATABASE_FAILURE.name(), alertDescription);
        sendErrorToEventResource(queueLb);
        return;
    }
    try {
        if (isRestAdapter()) {
            LOG.debug("Deleting connection throttle in STM...");
            reverseProxyLoadBalancerStmService.deleteConnectionThrottle(dbLoadBalancer);
            LOG.debug("Successfully deleted connection throttle in Zeus.");
        } else {
            LOG.debug("Deleting connection throttle in ZXTM...");
            reverseProxyLoadBalancerService.deleteConnectionThrottle(dbLoadBalancer);
            LOG.debug("Successfully deleted connection throttle in Zeus.");
        }
    } catch (Exception e) {
        loadBalancerService.setStatus(dbLoadBalancer, LoadBalancerStatus.ERROR);
        String alertDescription = String.format("Error deleting connection throttle in Zeus for loadbalancer '%d'.", queueLb.getId());
        LOG.error(alertDescription, e);
        notificationService.saveAlert(queueLb.getAccountId(), queueLb.getId(), e, ZEUS_FAILURE.name(), alertDescription);
        sendErrorToEventResource(queueLb);
        return;
    }
    connectionThrottleService.delete(dbLoadBalancer);
    loadBalancerService.setStatus(dbLoadBalancer, LoadBalancerStatus.ACTIVE);
    // Add atom entry
    String atomTitle = "Connection Throttle Successfully Deleted";
    String atomSummary = "Connection throttle successfully deleted";
    try {
        //TODO: fix the event...
        notificationService.saveConnectionLimitEvent(queueLb.getUserName(), dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), dbLoadBalancer.getConnectionLimit().getId(), atomTitle, atomSummary, DELETE_CONNECTION_THROTTLE, DELETE, INFO);
    } catch (PersistenceException pe) {
        LOG.error("Error saving the connection throttle event for load balancer: " + queueLb.getId() + "for account: " + queueLb.getAccountId());
    }
    LOG.info(String.format("Delete connection throttle operation complete for load balancer '%d'.", queueLb.getId()));
}
Example 79
Project: candlepin-master  File: UeberCertificateCuratorTests.java View source code
@Test
public void ensureDuplicateCertificateCreationFailsForAnOwner() {
    // This should never happen in code, but adding a test to make
    // sure that if there was ever an attempt to add more than one
    // cert to an owner, the DB would block it.
    //
    // The second create should throw a constraint violation.
    this.createUeberCert(owner);
    try {
        this.createUeberCert(owner);
        fail("Expected an exception due to multiple certs for the owner.");
    } catch (PersistenceException e) {
        assertTrue(e.getCause() != null && e.getCause() instanceof ConstraintViolationException);
    }
}
Example 80
Project: clinic-softacad-master  File: ConfigurationHelper.java View source code
public static FlushMode getFlushMode(Object value) {
    FlushMode flushMode = null;
    if (value instanceof FlushMode) {
        flushMode = (FlushMode) value;
    } else if (value instanceof javax.persistence.FlushModeType) {
        flushMode = ConfigurationHelper.getFlushMode((javax.persistence.FlushModeType) value);
    } else if (value instanceof String) {
        flushMode = ConfigurationHelper.getFlushMode((String) value);
    }
    if (flushMode == null) {
        throw new PersistenceException("Unable to parse org.hibernate.flushMode: " + value);
    }
    return flushMode;
}
Example 81
Project: deltaspike-master  File: QueryStringExtractorFactoryTest.java View source code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("toString")) {
        return "Unknown provider wrapper for tests.";
    }
    if (method.getName().equals("unwrap")) {
        Class<?> clazz = (Class<?>) args[0];
        if (clazz.getName().contains("hibernate") || clazz.getName().contains("openjpa") || clazz.getName().contains("eclipse")) {
            return createProxy(clazz);
        } else {
            throw new PersistenceException("Unable to unwrap for " + clazz);
        }
    }
    return null;
}
Example 82
Project: FiWare-Template-Handler-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 83
Project: graniteds-master  File: TestTideHome.java View source code
@Test
public void testQueryCallGDS775() {
    boolean error = false;
    try {
        invokeComponent("baseQuery", "refresh", new Object[] {}, new Object[] { new Object[] { "baseQuery", "firstResult", 0 }, new Object[] { "baseQuery", "maxResults", 10 } }, new String[] { "baseQuery.resultList" }, null);
    } catch (ServiceException e) {
        if (PersistenceException.class.isInstance(e.getCause()))
            error = true;
    }
    Assert.assertTrue("Persistence exception received", error);
}
Example 84
Project: guice-jpa-master  File: ManualLocalTransactionsConfidenceTest.java View source code
public void testThrowingCleanupInterceptorConfidence() {
    Exception e = null;
    try {
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        injector.getInstance(TransactionalObject.class).runOperationInTxn();
        fail();
    } catch (RuntimeException re) {
        e = re;
        System.out.println("\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********");
        re.printStackTrace(System.out);
        System.out.println("\n\n**********************************************************************************");
    }
    assertNotNull("No exception was thrown!", e);
    assertTrue("Exception thrown was not what was expected (i.e. commit-time)", e instanceof PersistenceException);
}
Example 85
Project: hibernate-core-ogm-master  File: ConfigurationHelper.java View source code
public static FlushMode getFlushMode(Object value) {
    FlushMode flushMode = null;
    if (value instanceof FlushMode) {
        flushMode = (FlushMode) value;
    } else if (value instanceof javax.persistence.FlushModeType) {
        flushMode = ConfigurationHelper.getFlushMode((javax.persistence.FlushModeType) value);
    } else if (value instanceof String) {
        flushMode = ConfigurationHelper.getFlushMode((String) value);
    }
    if (flushMode == null) {
        throw new PersistenceException("Unable to parse org.hibernate.flushMode: " + value);
    }
    return flushMode;
}
Example 86
Project: jagger-master  File: CustomMetricSummaryFetcher.java View source code
/**
     * @param taskIds  ids of all tasks
     * @param metricId identifier of metric
     * @return list of object[] (value, sessionId, metricId, taskDataId)
     */
protected List<Object[]> getCustomMetricsDataNewModel(Set<Long> taskIds, Set<String> metricId) {
    try {
        if (taskIds.isEmpty() || metricId.isEmpty()) {
            return Collections.emptyList();
        }
        return entityManager.createQuery("SELECT summary.total, summary.metricDescription.taskData.sessionId, summary.metricDescription.metricId, summary" + ".metricDescription.taskData.id " + "FROM MetricSummaryEntity AS summary " + "WHERE summary.metricDescription.taskData.id IN (:ids) " + "AND summary.metricDescription.metricId IN (:metricIds)").setParameter("ids", taskIds).setParameter("metricIds", metricId).getResultList();
    } catch (PersistenceException e) {
        log.debug("Could not fetch metric summary values from MetricSummaryEntity: {}", DataProcessingUtil.getMessageFromLastCause(e));
        return Collections.emptyList();
    }
}
Example 87
Project: jboss-jpa-master  File: MinimalBeanValidationTestCase.java View source code
@Test
public //in fact BV is initialized by Hibernate in this case
void testBeanValidation() throws Exception {
    transactionManager.begin();
    EntityManager em = persistenceUnit.getContainerEntityManagerFactory().createEntityManager();
    try {
        Person p = new Person();
        p.setId(2);
        p.setName("Caroline");
        //invalid nickname
        p.setNickname("C");
        em.persist(p);
        em.joinTransaction();
        em.flush();
        fail("Bean validation should have been triggered");
    } catch (ConstraintViolationException e) {
    } catch (PersistenceException e) {
        assertEquals("Should be a validation exception", e.getCause().getClass(), ConstraintViolationException.class);
    } finally {
        transactionManager.rollback();
        em.close();
    }
}
Example 88
Project: jenkow-plugin-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 89
Project: jubula.core-master  File: ObjectMappingManager.java View source code
/**
     * Persists all mappings that have been added to this manager.
     * 
     * @throws PMException 
     *              If a database error occurs.
     * @throws ProjectDeletedException 
     *              If the project was deleted in another transaction.
     */
public void saveMappings() throws PMException, ProjectDeletedException {
    try {
        for (IAUTMainPO aut : m_objectMappings.keySet()) {
            if (aut != null) {
                EditSupport editSupport = new EditSupport(aut, null);
                editSupport.reinitializeEditSupport();
                editSupport.lockWorkVersion();
                IAUTMainPO workVersion = (IAUTMainPO) editSupport.getWorkVersion();
                IObjectMappingPO objMap = workVersion.getObjMap();
                // add mappings
                Map<IComponentIdentifier, String> autObjectMapping = m_objectMappings.get(aut);
                if (autObjectMapping != null) {
                    for (IComponentIdentifier ci : autObjectMapping.keySet()) {
                        objMap.addObjectMappingAssoziation(autObjectMapping.get(ci), ci);
                    }
                }
                editSupport.saveWorkVersion();
                DataEventDispatcher.getInstance().fireDataChangedListener(objMap, DataState.StructureModified, UpdateState.all);
            }
        }
    } catch (PersistenceException e) {
        PersistenceManager.handleDBExceptionForMasterSession(null, e);
    }
}
Example 90
Project: moskito-central-master  File: PSQLStorage.java View source code
@Override
public void configure(String configurationName) {
    config = new PSQLStorageConfig();
    if (configurationName == null)
        return;
    try {
        ConfigurationManager.INSTANCE.configureAs(config, configurationName);
    } catch (IllegalArgumentException e) {
        log.warn("Couldn't configure PSQLStorage with " + configurationName + " , working with default values");
    }
    Map<String, String> map = new HashMap<String, String>();
    map.put("javax.persistence.jdbc.driver", config.getDriver());
    map.put("javax.persistence.jdbc.url", config.getUrl());
    map.put("javax.persistence.jdbc.user", config.getUserName());
    map.put("javax.persistence.jdbc.password", config.getPassword());
    if (config.getHibernateDialect() != null) {
        map.put("hibernate.dialect", config.getHibernateDialect());
    }
    map.put("hibernate.hbm2ddl.auto", "update");
    map.put("hibernate.show_sql", "true");
    try {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, map);
    } catch (PersistenceException e) {
        log.error("Persistence.createEntityManagerFactory({}, ({})", PERSISTENCE_UNIT_NAME, map, e);
    }
}
Example 91
Project: openjpa-master  File: TestAutoIncrement.java View source code
/**
     * Create sequence so that the test does not require manual intervention in database.
     */
private void createSequence(String sequence) {
    OpenJPAEntityManagerFactorySPI factorySPI = createEMF();
    OpenJPAEntityManagerSPI em = factorySPI.createEntityManager();
    try {
        em.getTransaction().begin();
        Query q = em.createNativeQuery("CREATE SEQUENCE " + sequence + " START WITH 1");
        q.executeUpdate();
        em.getTransaction().commit();
    } catch (PersistenceException e) {
        em.getTransaction().rollback();
    }
    closeEM(em);
    closeEMF(factorySPI);
}
Example 92
Project: oregami-server-master  File: StartHelper.java View source code
public static void init(String localConfigFilename) {
    configFilename = localConfigFilename;
    OregamiConfiguration configuration = createConfiguration(localConfigFilename);
    Properties properties = createPropertiesFromConfiguration(configuration);
    jpaUnit = configuration.getDatabaseConfiguration().getJpaUnit();
    JpaPersistModule jpaPersistModule = new JpaPersistModule(jpaUnit);
    jpaPersistModule.properties(properties);
    injector = Guice.createInjector(jpaPersistModule, new OregamiGuiceModule());
    try {
        injector.getInstance(PersistService.class).start();
    } catch (PersistenceException e) {
        throw new RuntimeException("Database error", e);
    }
}
Example 93
Project: palava-jpa-aspectj-master  File: EntityTransactionAspect.java View source code
// CHECKSTYLE:OFF
@Around("execution(@de.cosmocode.palava.jpa.Transactional * *.*(..))")
public Object transactional(ProceedingJoinPoint point) {
    checkInjected();
    final EntityManager manager = currentManager.get();
    LOG.trace("Retrieved entitymanager {}", manager);
    final EntityTransaction tx = manager.getTransaction();
    LOG.trace("Using transaction {}", tx);
    final boolean local = !tx.isActive();
    if (local) {
        LOG.debug("Beginning automatic transaction {}", tx);
        tx.begin();
    } else {
        LOG.trace("Transaction {} already active", tx);
    }
    final Object returnValue;
    try {
        returnValue = point.proceed();
    } catch (Throwable e) {
        try {
            if (local && (tx.isActive() || tx.getRollbackOnly())) {
                LOG.debug("Rolling back local/active transaction {}", tx);
                tx.rollback();
            } else if (!tx.getRollbackOnly()) {
                LOG.debug("Setting transaction {} as rollback only", tx);
                tx.setRollbackOnly();
            }
        } catch (PersistenceException inner) {
            LOG.error("Rollback failed", inner);
        } finally {
            throw Throwables.sneakyThrow(e);
        }
    }
    if (local && tx.isActive()) {
        if (tx.getRollbackOnly()) {
            LOG.debug("Rolling back marked transaction {}", tx);
            tx.rollback();
        } else {
            try {
                tx.commit();
                LOG.debug("Committed automatic transaction {}", tx);
            } catch (PersistenceException e) {
                if (tx.isActive()) {
                    try {
                        LOG.debug("Rolling back transaction {}", tx);
                        tx.rollback();
                    } catch (PersistenceException inner) {
                        LOG.error("Rollback failed", inner);
                    }
                }
                throw e;
            }
        }
    } else {
        LOG.trace("Not committing non-local transaction {}", tx);
    }
    return returnValue;
}
Example 94
Project: palava-media-master  File: AbstractAssetService.java View source code
@Transactional
@Override
public T create(final T entity) {
    createEvent.eventAssetCreate(entity);
    final Store store = getStore();
    final String identifier;
    final InputStream stream = entity.getStream();
    try {
        identifier = store.create(stream);
    } catch (IOException e) {
        throw new PersistenceException(e);
    }
    entity.setStoreIdentifier(identifier);
    try {
        final T returnValue = super.create(entity);
        createdEvent.eventAssetCreated(entity);
        return returnValue;
    /* CHECKSTYLE:OFF */
    } catch (RuntimeException e) {
        entity.setStoreIdentifier(null);
        try {
            LOG.warn("Saving asset {} failed. Removing binary data from store", entity);
            store.delete(identifier);
        } catch (IOException inner) {
            LOG.warn("Unable to delete binary data from store for " + identifier, inner);
        }
        throw e;
    }
}
Example 95
Project: seyhan-master  File: Ws2WsDataTransfers.java View source code
public static Result transfer() {
    if (!CacheUtils.isSuperUser())
        return Application.getForbiddenResult();
    Form<Ws2WsTransferModel> filledForm = dataForm.bindFromRequest();
    if (filledForm.hasErrors()) {
        return badRequest(ws2ws_form.render(filledForm));
    } else {
        Ws2WsTransferModel model = filledForm.get();
        checkConstraints(filledForm);
        if (filledForm.hasErrors()) {
            return badRequest(ws2ws_form.render(filledForm));
        }
        Ebean.beginTransaction();
        try {
            Ws2WsTransferManager.transfer(model);
            Ebean.commitTransaction();
            flash("success", Messages.get("saved", "Transfer"));
        } catch (PersistenceException pe) {
            Ebean.rollbackTransaction();
            flash("error", Messages.get("unexpected.problem.occured", pe.getMessage()));
            log.error("ERROR", pe);
            return badRequest(ws2ws_form.render(filledForm));
        }
    }
    return ok(ws2ws_form.render(filledForm));
}
Example 96
Project: ToHPluginUtils-master  File: RetryingAvajeTransactionStrategy.java View source code
/* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.transaction.TransactionStrategy#execute(org.tyrannyofheaven.bukkit.util.transaction.TransactionCallback, boolean)
     */
@Override
public <T> T execute(TransactionCallback<T> callback, boolean readOnly) {
    if (callback == null)
        throw new IllegalArgumentException("callback cannot be null");
    PersistenceException savedPE = null;
    for (int attempt = -1; attempt < maxRetries; attempt++) {
        try {
            if (getPreBeginHook() != null)
                getPreBeginHook().preBegin(readOnly);
            getEbeanServer().beginTransaction();
            try {
                T result = callback.doInTransaction();
                if (getPreCommitHook() != null)
                    getPreCommitHook().preCommit(readOnly);
                getEbeanServer().commitTransaction();
                return result;
            } finally {
                getEbeanServer().endTransaction();
            }
        } catch (PersistenceException e) {
            savedPE = e;
            continue;
        } catch (ErrorRuntimeException |  e) {
            throw e;
        } catch (Throwable t) {
            throw new TransactionException(t);
        }
    }
    // At this point, we've run out of attempts
    throw savedPE;
}
Example 97
Project: URLManager-master  File: AEPersistenceInhibitor.java View source code
public void inhibitPersistenceException(PersistenceException e) {
    LogFactory.getLog(AEPersistenceInhibitor.class).debug("Inhibiting persistence exception", e);
    if (e.getCause() instanceof ConstraintViolationException) {
        // TODO : create the appropriate exception with its appropriate HTTP error code
        throw new InternalErrorException("Constraint violation exception", e);
    } else if (e.getCause() instanceof SQLGrammarException) {
        throw new InternalErrorException("SQL grammar error", e);
    } else {
        throw new InternalErrorException("Persistence error : " + e.getMessage(), e);
    }
}
Example 98
Project: voms-admin-server-master  File: OrgDbHibernateSessionFilter.java View source code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    chain.doFilter(request, response);
    SessionFactory sf = OrgDBSessionFactory.getSessionFactory();
    try {
        if (sf == null) {
            throw new VOMSFatalException("OrgDBSessionFactory not initialized!");
        }
        if (sf.getCurrentSession() == null) {
            LOG.debug("No session opened with CERN HR db.");
            return;
        }
        if (sf.getCurrentSession().getTransaction() == null) {
            LOG.debug("No transaction opened with CERN HR db.");
            return;
        }
        if (!sf.getCurrentSession().getTransaction().isActive()) {
            LOG.debug("Current CERN HR db transaction is not active");
            return;
        }
        sf.getCurrentSession().getTransaction().commit();
    } catch (RollbackException e) {
        LOG.error("Error committing CERN HR db transaction: " + e.getMessage(), e);
        try {
            sf.getCurrentSession().getTransaction().rollback();
        } catch (PersistenceException pe) {
            LOG.error("Error rolling back CERN HR db transaction: " + pe.getMessage(), pe);
        }
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
    } finally {
        if (sf.getCurrentSession() != null) {
            try {
                sf.getCurrentSession().close();
            } catch (HibernateException e) {
                LOG.error("Error closing CERN HR db session: " + e.getMessage(), e);
            }
        }
    }
}
Example 99
Project: x-guice-master  File: DBInterceptor.java View source code
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    // I don't care bridge methods so much because nested invocations cost almost nothing.
    // Significant resources spend on DB connect only, but in case of bridge methods connection
    // obtained only in the most deep invocation. In this case outer invocation became
    // connection and/or transaction owner and closes it properly.
    // In case of REQUIRES_NEW nested invocations create extra UnitOfWork, but
    // connection obtained only in the most deep one and almost no extra resources wasted.
    Method method = invocation.getMethod();
    DB config = method.getAnnotation(DB.class);
    if (config == null) {
        throw new IllegalStateException("@DB annotation not found on " + method);
    }
    // method retry processing
    int retries = 0;
    while (true) {
        try {
            return invoke0(config.transaction(), invocation);
        } catch (PersistenceException e) {
            if (e.getCause() instanceof SQLTransientException && retries++ < config.retries()) {
                if (delayRetry(retries)) {
                    logger.info(String.format("Retry #%d of %s", retries, method), e);
                    continue;
                }
            }
            throw e;
        }
    }
}
Example 100
Project: xbpm5-master  File: EntityManagerSessionImpl.java View source code
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
Example 101
Project: arquillian-container-spring-showcase-master  File: JpaStockRepository.java View source code
/**
     * {@inheritDoc}
     */
@Override
public long save(Stock stock) {
    // validates the input
    validateNoNull(stock, "stock");
    validateNotEmpty(stock.getSymbol(), "symbol");
    EntityManager entityManager = getEntityManager();
    try {
        entityManager.getTransaction().begin();
        // persists the entity
        entityManager.persist(stock);
        entityManager.getTransaction().commit();
        // return the newly created id for the entity
        return stock.getId();
    } catch (PersistenceException exc) {
        entityManager.getTransaction().rollback();
        throw exc;
    }
}