javax.persistence.PersistenceException Java Examples

The following examples show how to use javax.persistence.PersistenceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncryptedRawTransactionDAOTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void saveDoesntAllowNullEncryptedKey() {

    EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction();
    encryptedRawTransaction.setHash(new MessageHash(new byte[] {5}));
    encryptedRawTransaction.setEncryptedPayload(new byte[] {5});
    encryptedRawTransaction.setNonce("nonce".getBytes());
    encryptedRawTransaction.setSender("from".getBytes());

    final Throwable throwable =
            catchThrowable(
                    () -> {
                        encryptedRawTransactionDAO.save(encryptedRawTransaction);
                        entityManager.flush();
                    });

    assertThat(throwable)
            .isInstanceOf(PersistenceException.class)
            .hasMessageContaining("NOT NULL constraint failed");
}
 
Example #2
Source File: EncryptedTransactionDAOTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void saveDoesntAllowNullEncodedPayload() {

    EncryptedTransaction encryptedTransaction = new EncryptedTransaction();
    encryptedTransaction.setHash(new MessageHash(new byte[] {5}));

    final Throwable throwable =
            catchThrowable(
                    () -> {
                        encryptedTransactionDAO.save(encryptedTransaction);
                        entityManager.flush();
                    });

    assertThat(throwable)
            .isInstanceOf(PersistenceException.class)
            .hasMessageContaining("integrity constraint violation: NOT NULL check constraint");
}
 
Example #3
Source File: OrganizationDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createOrganization(Organization pOrganization) throws OrganizationAlreadyExistsException, CreationException {
    try {
        //the EntityExistsException is thrown only when flush occurs
        if (pOrganization.getName().trim().equals(""))
            throw new CreationException();
        em.persist(pOrganization);
        em.flush();
    } catch (EntityExistsException pEEEx) {
        throw new OrganizationAlreadyExistsException(pOrganization);
    } catch (PersistenceException pPEx) {
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        throw new CreationException();
    }
}
 
Example #4
Source File: CircleServiceTest.java    From rest-example with Apache License 2.0 6 votes vote down vote up
/**
 * Tests finding all circle entities when there is an error occurring in the repository.
 * Expected result:
 * There should be a flux returned from the service.
 * There should be an error from the mono containing an entity not found exception.
 */
@Test
public void findAllPersistenceErrorTest() {
    /* Set up repository mock as to generate error when find is attempted. */
    Mockito
        .when(mServiceRepository.findAll())
        .thenThrow(PersistenceException.class);

    /* Attempt the find. */
    final Flux<Circle> theFoundCirclesFlux = mServiceUnderTest.findAll();

    /* Verify that there is an error from the returned mono containing an exception . */
    StepVerifier
        .create(theFoundCirclesFlux)
        .expectError(PersistenceException.class)
        .verify();
}
 
Example #5
Source File: HibernateJpaDialect.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Nullable
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
	FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session);
	Assert.state(flushMode != null, "No FlushMode from Session");
	if (readOnly) {
		// We should suppress flushing for a read-only transaction.
		if (!flushMode.equals(FlushMode.MANUAL)) {
			session.setFlushMode(FlushMode.MANUAL);
			return flushMode;
		}
	}
	else {
		// We need AUTO or COMMIT for a non-read-only transaction.
		if (flushMode.lessThan(FlushMode.COMMIT)) {
			session.setFlushMode(FlushMode.AUTO);
			return flushMode;
		}
	}
	// No FlushMode change needed...
	return null;
}
 
Example #6
Source File: JpaTransactionManager.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void doRollback(DefaultTransactionStatus status) {
	JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
	if (status.isDebug()) {
		logger.debug("Rolling back JPA transaction on EntityManager [" +
				txObject.getEntityManagerHolder().getEntityManager() + "]");
	}
	try {
		EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
		if (tx.isActive()) {
			tx.rollback();
		}
	}
	catch (PersistenceException ex) {
		throw new TransactionSystemException("Could not roll back JPA transaction", ex);
	}
	finally {
		if (!txObject.isNewEntityManagerHolder()) {
			// Clear all pending inserts/updates/deletes in the EntityManager.
			// Necessary for pre-bound EntityManagers, to avoid inconsistent state.
			txObject.getEntityManagerHolder().getEntityManager().clear();
		}
	}
}
 
Example #7
Source File: PersistenceUnitTransactionTypeHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static PersistenceUnitTransactionType interpretTransactionType(Object value) {
	if ( value == null ) {
		return null;
	}

	if ( PersistenceUnitTransactionType.class.isInstance( value ) ) {
		return (PersistenceUnitTransactionType) value;
	}

	final String stringValue = value.toString();
	if ( StringHelper.isEmpty( stringValue ) ) {
		return null;
	}
	else if ( stringValue.equalsIgnoreCase( "JTA" ) ) {
		return PersistenceUnitTransactionType.JTA;
	}
	else if ( stringValue.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) {
		return PersistenceUnitTransactionType.RESOURCE_LOCAL;
	}
	else {
		throw new PersistenceException( "Unknown TransactionType: " + stringValue );
	}
}
 
Example #8
Source File: PathToPathLinkDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createPathToPathLink(PathToPathLink pPathToPathLink) throws CreationException, PathToPathLinkAlreadyExistsException {

        try {
            //the EntityExistsException is thrown only when flush occurs
            em.persist(pPathToPathLink);
            em.flush();
        } catch (EntityExistsException pEEEx) {
            LOGGER.log(Level.FINEST,null,pEEEx);
            throw new PathToPathLinkAlreadyExistsException(pPathToPathLink);
        } catch (PersistenceException pPEx) {
            LOGGER.log(Level.FINEST,null,pPEx);
            //EntityExistsException is case sensitive
            //whereas MySQL is not thus PersistenceException could be
            //thrown instead of EntityExistsException
            throw new CreationException();
        }
    }
 
Example #9
Source File: BankOrderManagementRepository.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public BankOrder save(BankOrder entity) {

  try {

    BankOrderService bankOrderService = Beans.get(BankOrderService.class);
    bankOrderService.generateSequence(entity);
    bankOrderService.setSequenceOnBankOrderLines(entity);
    if (entity.getStatusSelect() == BankOrderRepository.STATUS_DRAFT) {
      bankOrderService.updateTotalAmounts(entity);
    }

    return super.save(entity);
  } catch (Exception e) {
    throw new PersistenceException(e.getLocalizedMessage());
  }
}
 
Example #10
Source File: DocumentMasterDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createDocM(DocumentMaster pDocumentMaster) throws DocumentMasterAlreadyExistsException, CreationException {
    try {
        //the EntityExistsException is thrown only when flush occurs
        em.persist(pDocumentMaster);
        em.flush();
    } catch (EntityExistsException pEEEx) {
        LOGGER.log(Level.FINER,null,pEEEx);
        throw new DocumentMasterAlreadyExistsException(pDocumentMaster);
    } catch (PersistenceException pPEx) {
        //EntityExistsException is case sensitive
        //whereas MySQL is not thus PersistenceException could be
        //thrown instead of EntityExistsException
        LOGGER.log(Level.FINER,null,pPEx);
        throw new CreationException();
    }
}
 
Example #11
Source File: StorageServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test(expected = PersistenceException.class)
public void testDeleteStorageConstraintViolation() throws Exception
{
    // Create a storage unit entity that refers to a newly created storage.
    final StorageUnitEntity storageUnitEntity = storageUnitDaoTestHelper
        .createStorageUnitEntity(STORAGE_NAME, BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
            SUBPARTITION_VALUES, DATA_VERSION, LATEST_VERSION_FLAG_SET, BDATA_STATUS, STORAGE_UNIT_STATUS, NO_STORAGE_DIRECTORY_PATH);

    executeWithoutLogging(SqlExceptionHelper.class, new Command()
    {
        @Override
        public void execute()
        {
            // Delete the storage which is invalid because there still exists a storage unit entity that references it.
            StorageKey alternateKey = new StorageKey(storageUnitEntity.getStorage().getName());
            storageService.deleteStorage(alternateKey);
        }
    });
}
 
Example #12
Source File: BuildRecordTest.java    From pnc with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldProhibitDeletionOfNonTemporaryBuild() {
    // given
    int brId = 666;
    BuildRecord br = prepareBuildRecordBuilder().id(brId).temporaryBuild(false).build();

    em.getTransaction().begin();
    em.persist(br);
    em.getTransaction().commit();

    // when, then
    try {
        em.getTransaction().begin();
        em.remove(br);
        em.getTransaction().commit();
    } catch (PersistenceException ex) {
        em.getTransaction().rollback();
        BuildRecord obtainedBr = em.find(BuildRecord.class, brId);
        assertNotNull(obtainedBr);
        assertEquals(brId, obtainedBr.getId().intValue());
        return;
    }
    fail("Deletion of the standard BuildRecord should be prohibited.");
}
 
Example #13
Source File: JpaTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void doRollback(DefaultTransactionStatus status) {
	JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
	if (status.isDebug()) {
		logger.debug("Rolling back JPA transaction on EntityManager [" +
				txObject.getEntityManagerHolder().getEntityManager() + "]");
	}
	try {
		EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
		if (tx.isActive()) {
			tx.rollback();
		}
	}
	catch (PersistenceException ex) {
		throw new TransactionSystemException("Could not roll back JPA transaction", ex);
	}
	finally {
		if (!txObject.isNewEntityManagerHolder()) {
			// Clear all pending inserts/updates/deletes in the EntityManager.
			// Necessary for pre-bound EntityManagers, to avoid inconsistent state.
			txObject.getEntityManagerHolder().getEntityManager().clear();
		}
	}
}
 
Example #14
Source File: LocalContainerEntityManagerFactoryBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws PersistenceException {
	PersistenceUnitManager managerToUse = this.persistenceUnitManager;
	if (this.persistenceUnitManager == null) {
		this.internalPersistenceUnitManager.afterPropertiesSet();
		managerToUse = this.internalPersistenceUnitManager;
	}

	this.persistenceUnitInfo = determinePersistenceUnitInfo(managerToUse);
	JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();
	if (jpaVendorAdapter != null && this.persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {
		String rootPackage = jpaVendorAdapter.getPersistenceProviderRootPackage();
		if (rootPackage != null) {
			((SmartPersistenceUnitInfo) this.persistenceUnitInfo).setPersistenceProviderPackageName(rootPackage);
		}
	}

	super.afterPropertiesSet();
}
 
Example #15
Source File: FastBootEntityManagerFactoryBuilder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
protected PersistenceException persistenceException(String message, Exception cause) {
    // Provide a comprehensible message if there is an issue with SSL support
    Throwable t = cause;
    while (t != null) {
        if (t instanceof NoSuchAlgorithmException) {
            message += "Unable to enable SSL support. You might be in the case where you used the `quarkus.ssl.native=false` configuration"
                    + " and SSL was not disabled automatically for your driver.";
            break;
        }

        if (t instanceof CommandAcceptanceException) {
            message = "Invalid import file. Make sure your statements are valid and properly separated by a semi-colon.";
            break;
        }

        t = t.getCause();
    }

    return new PersistenceException(getExceptionHeader() + message, cause);
}
 
Example #16
Source File: LocalEntityManagerFactoryBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the EntityManagerFactory for the given configuration.
 * @throws javax.persistence.PersistenceException in case of JPA initialization errors
 */
@Override
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
	if (logger.isInfoEnabled()) {
		logger.info("Building JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'");
	}
	PersistenceProvider provider = getPersistenceProvider();
	if (provider != null) {
		// Create EntityManagerFactory directly through PersistenceProvider.
		EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
		if (emf == null) {
			throw new IllegalStateException(
					"PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" +
					getPersistenceUnitName() + "'");
		}
		return emf;
	}
	else {
		// Let JPA perform its standard PersistenceProvider autodetection.
		return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
	}
}
 
Example #17
Source File: LocalEntityManagerFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Initialize the EntityManagerFactory for the given configuration.
 * @throws javax.persistence.PersistenceException in case of JPA initialization errors
 */
@Override
protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
	if (logger.isDebugEnabled()) {
		logger.debug("Building JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'");
	}
	PersistenceProvider provider = getPersistenceProvider();
	if (provider != null) {
		// Create EntityManagerFactory directly through PersistenceProvider.
		EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
		if (emf == null) {
			throw new IllegalStateException(
					"PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" +
					getPersistenceUnitName() + "'");
		}
		return emf;
	}
	else {
		// Let JPA perform its standard PersistenceProvider autodetection.
		return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap());
	}
}
 
Example #18
Source File: OpenJpaDialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
		FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
		if (fetchPlan instanceof JDBCFetchPlan) {
			IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
			((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
		}
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly()) {
		// Like with EclipseLink, make sure to start the logic transaction early so that other
		// participants using the connection (such as JdbcTemplate) run in a transaction.
		openJpaEntityManager.beginStore();
	}

	// Custom implementation for OpenJPA savepoint handling
	return new OpenJpaTransactionData(openJpaEntityManager);
}
 
Example #19
Source File: AccountingReportManagementRepository.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public AccountingReport save(AccountingReport accountingReport) {
  try {

    if (accountingReport.getRef() == null) {

      String seq = accountingReportService.getSequence(accountingReport);
      accountingReportService.setSequence(accountingReport, seq);
    }

    return super.save(accountingReport);
  } catch (Exception e) {
    JPA.em().getTransaction().rollback();
    JPA.runInTransaction(() -> TraceBackService.trace(e));
    JPA.em().getTransaction().begin();
    throw new PersistenceException(e.getLocalizedMessage());
  }
}
 
Example #20
Source File: QueryDAO.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
public void createQuery(Query query) throws CreationException, QueryAlreadyExistsException {
    try {

        QueryRule queryRule = query.getQueryRule();

        if (queryRule != null) {
            persistQueryRules(queryRule);
        }

        QueryRule pathDataQueryRule = query.getPathDataQueryRule();

        if (pathDataQueryRule != null) {
            persistQueryRules(pathDataQueryRule);
        }

        em.persist(query);
        em.flush();
        persistContexts(query, query.getContexts());
    } catch (EntityExistsException pEEEx) {
        LOGGER.log(Level.FINEST, null, pEEEx);
        throw new QueryAlreadyExistsException(query);
    } catch (PersistenceException pPEx) {
        LOGGER.log(Level.FINEST, null, pPEx);
        throw new CreationException();
    }
}
 
Example #21
Source File: ContextDataJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    try {
        final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
        final ObjectNode root = factory.objectNode();
        contextData.forEach(new BiConsumer<String, Object>() {
            @Override
            public void accept(final String key, final Object value) {
                // we will cheat here and write the toString of the Object... meh, but ok.
                root.put(key, String.valueOf(value));
            }
        });
        return OBJECT_MAPPER.writeValueAsString(root);
    } catch (final Exception e) {
        throw new PersistenceException("Failed to convert contextData to JSON string.", e);
    }
}
 
Example #22
Source File: CSSJsoupPhlocContentAdapterImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Adapt the external css. 
 */
private void adaptExternalCss() {
    for (Element el : externalCssElements) {
        List<CSSMediaQuery> mediaList = getListOfMediaFromAttributeValue(el);
        String resourcePath = el.attr("abs:href");
        getExternalResourceAndAdapt(resourcePath, mediaList);
    }
    Set<Long> relatedCssIdSet = new HashSet<>();
    // At the end of the document we link each external css that are
    // already fetched and that have been encountered in the SSP to the SSP.
    LOGGER.debug("Found " + relatedExternalCssSet.size() + 
            " external css in "+ getSSP().getURI());
    for (StylesheetContent cssContent : relatedExternalCssSet) {
        if (cssContent.getAdaptedContent() == null) {
            cssContent.setAdaptedContent(CSS_ON_ERROR);
        }
        LOGGER.debug("Create relation between "+getSSP().getURI() +
                " and " + cssContent.getURI());
        // to avoid fatal error when persist weird sourceCode
        try {
            // the content is saved only when the id is null which means 
            // that the content hasn't been persisted yet. Otherwise, the
            // save is uneeded and the id is used to create the relation 
            // with the current SSP
            if (cssContent.getId() == null) {
                cssContent = (StylesheetContent)getContentDataService().saveOrUpdate(cssContent);
            }
            relatedCssIdSet.add(cssContent.getId());
        } catch (PersistenceException | DataException pe) {
            adaptedContentOnError(cssContent, relatedCssIdSet);
        }
    }
    getContentDataService().saveContentRelationShip(getSSP(), relatedCssIdSet);
}
 
Example #23
Source File: JPARecipientRewriteTable.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Update the mapping for the given user and domain
 *
 * @return true if update was successfully
 */
private boolean doUpdateMapping(MappingSource source, String mapping) throws RecipientRewriteTableException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        int updated = entityManager
            .createNamedQuery("updateMapping")
            .setParameter("targetAddress", mapping)
            .setParameter("user", source.getFixedUser())
            .setParameter("domain", source.getFixedDomain())
            .executeUpdate();
        transaction.commit();
        if (updated > 0) {
            return true;
        }
    } catch (PersistenceException e) {
        LOGGER.debug("Failed to update mapping", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new RecipientRewriteTableException("Unable to update mapping", e);
    } finally {
        EntityManagerUtils.safelyClose(entityManager);
    }
    return false;
}
 
Example #24
Source File: CafeResource.java    From javaee-docker with MIT License 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createCoffee(Coffee coffee) {
	try {
		coffee = this.cafeRepository.persistCoffee(coffee);
		return Response.created(URI.create("/" + coffee.getId())).build();
	} catch (PersistenceException e) {
		logger.log(Level.SEVERE, "Error creating coffee {0}: {1}.", new Object[] { coffee, e });
		throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
	}
}
 
Example #25
Source File: AddressBaseRepository.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Address save(Address entity) {

  entity.setFullName(addressService.computeFullName(entity));
  try {
    addressService.updateLatLong(entity);
  } catch (Exception e) {
    throw new PersistenceException(e);
  }

  return super.save(entity);
}
 
Example #26
Source File: ContextStackJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: JpaLockingStrategy.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 **/
@Override
@Transactional(readOnly = false)
public boolean acquire() {
    Lock lock;
    try {
        lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE);
    } catch (final PersistenceException e) {
        logger.debug("{} failed querying for {} lock.", uniqueId, applicationId, e);
        return false;
    }

    boolean result = false;
    if (lock != null) {
        final DateTime expDate = new DateTime(lock.getExpirationDate());
        if (lock.getUniqueId() == null) {
            // No one currently possesses lock
            logger.debug("{} trying to acquire {} lock.", uniqueId, applicationId);
            result = acquire(entityManager, lock);
        } else if (new DateTime().isAfter(expDate)) {
            // Acquire expired lock regardless of who formerly owned it
            logger.debug("{} trying to acquire expired {} lock.", uniqueId, applicationId);
            result = acquire(entityManager, lock);
        }
    } else {
        // First acquisition attempt for this applicationId
        logger.debug("Creating {} lock initially held by {}.", applicationId, uniqueId);
        result = acquire(entityManager, new Lock());
    }
    return result;
}
 
Example #28
Source File: ContextMapJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public String convertToDatabaseColumn(final Map<String, String> contextMap) {
    if (contextMap == null) {
        return null;
    }

    try {
        return OBJECT_MAPPER.writeValueAsString(contextMap);
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert map to JSON string.", e);
    }
}
 
Example #29
Source File: CafeResource.java    From jakartaee-azure with MIT License 5 votes vote down vote up
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response createCoffee(Coffee coffee) {
	try {
		coffee = this.cafeRepository.persistCoffee(coffee);
		return Response.created(URI.create("/" + coffee.getId())).build();
	} catch (PersistenceException e) {
		logger.log(Level.SEVERE, "Error creating coffee {0}: {1}.", new Object[] { coffee, e });
		throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
	}
}
 
Example #30
Source File: ExpenseHRRepository.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Expense save(Expense expense) {
  try {
    expense = super.save(expense);
    Beans.get(ExpenseService.class).setDraftSequence(expense);
    if (expense.getStatusSelect() == ExpenseRepository.STATUS_DRAFT) {
      Beans.get(ExpenseService.class).completeExpenseLines(expense);
    }

    return expense;
  } catch (Exception e) {
    throw new PersistenceException(e.getLocalizedMessage());
  }
}