Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

In this page you can find the example usage for org.hibernate Session persist.

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:org.openscoring.service.RolesPermissionResource.java

License:Open Source License

@PUT
@Produces(MediaType.APPLICATION_JSON)/*  w  ww .j a  va2s.  com*/
public SimpleResponse addRoleAndPermission(RolesPermission rolesPermission) {
    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser.isAuthenticated() && currentUser.hasRole("admin")) {
        SimpleResponse simpleResponse = new SimpleResponse();
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction tx = session.beginTransaction();
            session.persist(rolesPermission);
            tx.commit();
            simpleResponse.setMessage("add role & permissions successfully");
            return simpleResponse;
        } catch (Exception e) {
            simpleResponse
                    .setMessage("add role & permissions not successfully! Error: [" + e.getMessage() + "]");
            return simpleResponse;
        }
    } else {
        throw new NotAuthorizedException("Sorry, You don't have permission to view this content!");
    }
}

From source file:org.openscoring.service.UserResource.java

License:Open Source License

@PUT
@Path("/role")
@Produces(MediaType.APPLICATION_JSON)/*w ww .j av a2 s .  com*/
public SimpleResponse addRole(UserRole userRole) {
    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser.isAuthenticated() && currentUser.hasRole("admin")) {
        SimpleResponse simpleResponse = new SimpleResponse();
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction tx = session.beginTransaction();
            session.persist(userRole);
            tx.commit();
            simpleResponse.setMessage("add role [" + userRole.getRoleName() + "] to user ["
                    + userRole.getUsername() + "] successfully");
            return simpleResponse;
        } catch (Exception e) {
            simpleResponse.setMessage("add role not successfully! Error: [" + e.getMessage() + "]");
            return simpleResponse;
        }
    } else {
        throw new NotAuthorizedException(
                "Sorry, only admin user can add role to user! Contact administrator please!");
    }
}

From source file:org.opentides.util.DBUtil.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
private static void executeHqlQuery(String className, List<String> headers, List<String> values,
        Session session) throws Exception {
    Object entity = Class.forName(className).newInstance();
    if (!(entity instanceof BaseEntity)) {
        throw new Exception("Entity is not an instance of BaseEntity");
    }/*from  w w  w. java2  s .  co  m*/
    for (int i = 0; i < headers.size(); i++) {
        String property = headers.get(i);
        String value = values.get(i);
        Class<?> type = CrudUtil.retrieveObjectType(entity, property);
        Method method = entity.getClass().getMethod(CrudUtil.getSetterMethodName(property),
                CrudUtil.retrieveObjectType(entity, property));
        _log.debug("Casting value : [" + value + "] to " + type.getName());
        if (type.equals(Long.class) && !StringUtil.isEmpty(value)) {
            method.invoke(entity, new Long(value));
        } else if (Enum.class.isAssignableFrom(type)) {
            method.invoke(entity, Enum.valueOf((Class<Enum>) type, value));
        } else if (BaseEntity.class.isAssignableFrom(type)) {
            Long id = Long.parseLong(value);
            method.invoke(entity, session.load(type, id));
        } else {
            method.invoke(entity, type.cast(value));
        }
    }
    BaseEntity baseEntity = (BaseEntity) entity;
    baseEntity.setSkipAudit(true);
    session.persist(baseEntity);
}

From source file:org.overlord.rtgov.activity.store.jpa.JPAActivityStore.java

License:Apache License

/**
 * {@inheritDoc}// w w w  .j a va  2s  .c  o m
 */
public void store(final List<ActivityUnit> activities) throws Exception {
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Store=" + new String(ActivityUtil.serializeActivityUnitList(activities)));
    }

    _jpaStore.withJpa(new JpaWork<Void>() {
        public Void perform(Session s) {
            for (int i = 0; i < activities.size(); i++) {
                s.persist(activities.get(i));
            }
            return null;
        }
    });
}

From source file:org.overlord.rtgov.analytics.situation.store.jpa.JPASituationStore.java

License:Apache License

/**
 * {@inheritDoc}/* w ww  . j a  v a 2 s  . c o m*/
 */
protected void doStore(final Situation situation) throws Exception {
    _jpaStore.withJpa(new JpaWork<Void>() {
        public Void perform(Session s) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("Persist situation id[" + situation.getId() + "] " + situation); //$NON-NLS-1$
            }
            s.persist(situation);
            return null;
        }
    });
}

From source file:org.overlord.rtgov.analytics.situation.store.jpa.JPASituationStoreTest.java

License:Apache License

private void persist(final Situation situation) {
    _jpaStore.withJpa(new JpaWork<Void>() {
        public Void perform(Session s) {
            s.persist(situation);
            return null;
        }/*  w  ww  .j a  v  a  2  s .com*/
    });

}

From source file:org.overlord.rtgov.ep.jpa.JPAEventProcessor.java

License:Apache License

/**
 * {@inheritDoc}/*from  w ww . j  a v  a 2  s .  c om*/
 */
public java.io.Serializable process(String source, final java.io.Serializable event, int retriesLeft)
        throws Exception {
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Process event '" + event + " from source '" + source + "' on JPA Event Processor");
    }

    _jpaStore.withJpa(new JpaWork<Void>() {
        public Void perform(Session s) {
            s.persist(event);
            return null;
        }
    });

    return null;
}

From source file:org.picketlink.idm.impl.store.hibernate.EvilBinaryTestCase.java

License:Open Source License

public void testBinary() throws Exception {
    begin();/* w ww . ja va  2s.co  m*/

    Session session = getSessionFactory().getCurrentSession();

    HibernateRealm realm = new HibernateRealm("default");
    session.persist(realm);

    HibernateIdentityObjectType userType = new HibernateIdentityObjectType("User");
    session.persist(userType);
    HibernateIdentityObject user1 = new HibernateIdentityObject("user1", userType, realm);
    session.persist(user1);

    Set<String> values1 = new HashSet<String>();
    values1.add("Val1");
    values1.add("Val2");
    values1.add("Val3");

    HibernateIdentityObjectAttribute attr = new HibernateIdentityObjectAttribute(user1, "simple1",
            HibernateIdentityObjectAttribute.TYPE_TEXT);
    attr.setTextValues(values1);
    user1.getAttributes().add(attr);

    commit();

    begin();

    session = getSessionFactory().getCurrentSession();

    user1 = (HibernateIdentityObject) session.get(HibernateIdentityObject.class, new Long(user1.getId()));

    Random random = new Random();

    // Small
    byte[] picture = new byte[512000];
    random.nextBytes(picture);

    attr = new HibernateIdentityObjectAttribute(user1, "simple2", HibernateIdentityObjectAttribute.TYPE_BINARY);
    attr.setBinaryValue(new HibernateIdentityObjectAttributeBinaryValue(picture));
    user1.addAttribute(attr);

    values1 = new HashSet<String>();
    values1.add("Val1");

    attr = new HibernateIdentityObjectAttribute(user1, "simple3", HibernateIdentityObjectAttribute.TYPE_TEXT);
    attr.setTextValues(values1);
    user1.getAttributes().add(attr);

    values1 = new HashSet<String>();
    values1.add("Val8");
    values1.add("Val15");

    attr = new HibernateIdentityObjectAttribute(user1, "simple4", HibernateIdentityObjectAttribute.TYPE_TEXT);
    attr.setTextValues(values1);
    user1.getAttributes().add(attr);

    commit();

    begin();

    session = getSessionFactory().getCurrentSession();

    user1 = (HibernateIdentityObject) session.get(HibernateIdentityObject.class, new Long(user1.getId()));

    // 900 kilobytes
    picture = new byte[921600];
    //      picture = new byte[2];
    random.nextBytes(picture);

    attr = new HibernateIdentityObjectAttribute(user1, "simple5", HibernateIdentityObjectAttribute.TYPE_BINARY);
    attr.setBinaryValue(new HibernateIdentityObjectAttributeBinaryValue(picture));
    user1.getAttributes().add(attr);

    commit();

    begin();

    session = getSessionFactory().getCurrentSession();

    user1 = (HibernateIdentityObject) session.get(HibernateIdentityObject.class, new Long(user1.getId()));

    Assert.assertEquals(5, user1.getAttributes().size());

    int binaryCount = ((Integer) session.createCriteria(HibernateIdentityObjectAttributeBinaryValue.class)
            .setProjection(Projections.rowCount()).uniqueResult()).intValue();

    Assert.assertEquals(2, binaryCount);

    int attrCount = ((Integer) session.createCriteria(HibernateIdentityObjectAttribute.class)
            .setProjection(Projections.rowCount()).uniqueResult()).intValue();

    Assert.assertEquals(5, attrCount);

    session.delete(user1);

    attrCount = ((Integer) session.createCriteria(HibernateIdentityObjectAttribute.class)
            .setProjection(Projections.rowCount()).uniqueResult()).intValue();

    Assert.assertEquals(0, attrCount);

    binaryCount = ((Integer) session.createCriteria(HibernateIdentityObjectAttributeBinaryValue.class)
            .setProjection(Projections.rowCount()).uniqueResult()).intValue();

    Assert.assertEquals(0, binaryCount);

    commit();

}

From source file:org.picketlink.idm.impl.store.hibernate.HibernateIdentityStoreImpl.java

License:Open Source License

public IdentityObjectRelationship createRelationship(IdentityStoreInvocationContext ctx,
        IdentityObject fromIdentity, IdentityObject toIdentity, IdentityObjectRelationshipType relationshipType,
        String name, boolean createNames) throws IdentityException {

    if (relationshipType == null) {
        throw new IllegalArgumentException("RelationshipType is null");
    }/*w  ww . ja v  a 2 s.  co m*/
    HibernateIdentityObject fromIO = safeGet(ctx, fromIdentity);
    HibernateIdentityObject toIO = safeGet(ctx, toIdentity);
    HibernateIdentityObjectRelationshipType type = getHibernateIdentityObjectRelationshipType(ctx,
            relationshipType);

    HibernateRealm realm = getRealm(getHibernateSession(ctx), ctx);

    if (!getSupportedFeatures().isRelationshipTypeSupported(fromIO.getIdentityType(), toIO.getIdentityType(),
            relationshipType)) {
        if (!isAllowNotDefinedIdentityObjectTypes()) {
            throw new IdentityException("Relationship not supported. RelationshipType[ "
                    + relationshipType.getName() + " ] " + "beetween: [ " + fromIO.getIdentityType().getName()
                    + " ] and [ " + toIO.getIdentityType().getName() + " ]");
        }
    }

    HibernateIdentityObjectRelationship relationship = null;
    HibernateRealm hibernateRealm = getRealm(getHibernateSession(ctx), ctx);

    if (name != null) {

        HibernateIdentityObjectRelationshipName relationshipName = (HibernateIdentityObjectRelationshipName) getHibernateSession(
                ctx).createCriteria(HibernateIdentityObjectRelationshipName.class).setCacheable(true)
                        .add(Restrictions.eq("name", name)).add(Restrictions.eq("realm", hibernateRealm))
                        .uniqueResult();

        if (relationshipName == null) {
            throw new IdentityException("Relationship name not present in the store");
        }

        relationship = new HibernateIdentityObjectRelationship(type, fromIO, toIO, relationshipName);
    } else {
        relationship = new HibernateIdentityObjectRelationship(type, fromIO, toIO);
    }

    try {
        Session session = getHibernateSession(ctx);
        session.persist(relationship);
        session.flush();

    } catch (HibernateException e) {
        if (log.isLoggable(Level.FINER)) {
            log.log(Level.FINER, "Exception occurred: ", e);
        }

        throw new IdentityException("Cannot create relationship: ", e);
    }

    return relationship;

}

From source file:org.picketlink.idm.impl.store.hibernate.HibernateIdentityStoreImpl.java

License:Open Source License

public void updateCredential(IdentityStoreInvocationContext ctx, IdentityObject identityObject,
        IdentityObjectCredential credential) throws IdentityException {

    if (credential == null) {
        throw new IllegalArgumentException();
    }/*from w  w  w .j a  v  a  2 s  . co m*/

    HibernateIdentityObject hibernateObject = safeGet(ctx, identityObject);

    Session hibernateSession = getHibernateSession(ctx);

    if (supportedFeatures.isCredentialSupported(hibernateObject.getIdentityType(), credential.getType())) {

        HibernateIdentityObjectCredentialType hibernateCredentialType = getHibernateIdentityObjectCredentialType(
                ctx, credential.getType());

        if (hibernateCredentialType == null) {
            throw new IllegalStateException(
                    "Credential type not present in this store: " + credential.getType().getName());
        }

        HibernateIdentityObjectCredential hibernateCredential = hibernateObject
                .getCredential(credential.getType());

        if (hibernateCredential == null) {
            hibernateCredential = new HibernateIdentityObjectCredential();
            hibernateCredential.setType(hibernateCredentialType);
            hibernateObject.addCredential(hibernateCredential);
        }

        Object value = null;

        // Handle generic impl

        if (credential.getEncodedValue() != null) {
            value = credential.getEncodedValue();
        } else {
            //TODO: support for empty password should be configurable
            value = credential.getValue();
        }

        if (value instanceof String) {
            hibernateCredential.setTextValue(value.toString());
        } else if (value instanceof byte[]) {
            HibernateIdentityObjectCredentialBinaryValue bv = new HibernateIdentityObjectCredentialBinaryValue(
                    (byte[]) value);
            getHibernateSession(ctx).persist(bv);
            hibernateCredential.setBinaryValue(bv);
        } else {
            throw new IdentityException("Not supported credential value: " + value.getClass());
        }

        hibernateSession.persist(hibernateCredential);

        hibernateObject.addCredential(hibernateCredential);

        hibernateSession.flush();

    } else {
        throw new IdentityException("CredentialType not supported for a given IdentityObjectType");
    }
}