Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

In this page you can find the example usage for javax.persistence EntityManager createQuery.

Prototype

public Query createQuery(CriteriaDelete deleteQuery);

Source Link

Document

Create an instance of Query for executing a criteria delete query.

Usage

From source file:de.egore911.opengate.services.PilotService.java

@POST
@Path("/register")
@Produces("application/json")
@Documentation("Register a new pilot. This will at first verify the login and email are "
        + "unique and the email is valid. After this it will register the pilot and send "
        + "and email to him to verify the address. The 'verify' will finalize the registration. "
        + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
        + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
        + "error occured an HTTP 500 will be sent.")
public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
        @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
    JSONObject jsonObject = new JSONObject();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Number n = (Number) em
            .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
            .setParameter("login", login).getSingleResult();
    if (n.intValue() > 0) {
        try {/*from www .  jav a2  s .c  o m*/
            StatusHelper.failed(jsonObject, "Duplicate login");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
            .setParameter("email", email).getSingleResult();
    if (n.intValue() > 0) {
        try {
            StatusHelper.failed(jsonObject, "Duplicate email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    InternetAddress recipient;
    try {
        recipient = new InternetAddress(email, login);
    } catch (UnsupportedEncodingException e1) {
        try {
            StatusHelper.failed(jsonObject, "Invalid email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Faction faction;
    try {
        faction = em.find(Faction.class, factionId);
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Invalid faction");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Vessel vessel;
    try {
        vessel = (Vessel) em
                .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                        + "order by vessel.techLevel asc")
                .setParameter("faction", faction).setMaxResults(1).getSingleResult();
        // TODO assign initical equipment as well
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Faction has no vessel");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    String passwordHash;
    String password = randomText();
    try {
        passwordHash = hashPassword(password);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    em.getTransaction().begin();
    try {
        Pilot pilot = new Pilot();
        pilot.setLogin(login);
        pilot.setCreated(new Date());
        pilot.setPasswordHash(passwordHash);
        pilot.setEmail(email);
        pilot.setFaction(faction);
        pilot.setVessel(vessel);
        pilot.setVerificationCode(randomText());
        em.persist(pilot);
        em.getTransaction().commit();
        try {
            // send e-mail to registered user containing the new password

            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                    + pilot.getLogin()
                    + " with your e-mail adress. The following credentials can be used for your account:\n"
                    + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                    + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                    + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                msg.addRecipient(Message.RecipientType.TO, recipient);
                msg.setSubject("Your Example.com account has been activated");
                msg.setText(msgBody);
                Transport.send(msg);

            } catch (AddressException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (MessagingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (UnsupportedEncodingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

            StatusHelper.ok(jsonObject);
            jsonObject.put("id", pilot.getKey().getId());
            jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
            // TODO properly wrap the vessel and its equipment/cargo
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (NoResultException e) {
        return Response.status(Status.FORBIDDEN).build();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

private Firma findFirma(EntityManager em, String strFirma) {
    Query q = em.createQuery("select distinct f from Firma f where f.nombre=:nombre");
    q.setParameter("nombre", strFirma);
    List<Firma> list = q.getResultList();
    if (list != null && list.size() > 0) {
        return list.get(0);
    }/*from  w ww .  ja  v  a2  s .  co m*/
    return null;
}

From source file:de.egore911.persistence.selector.AbstractSelector.java

public long count() {
    EntityManager em = EntityManagerUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<T> from = cq.from(getEntityClass());
    List<Predicate> predicates = generatePredicateList(builder, from, cq);
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    cq.select(builder.count(from));//  w  w  w.j a  v a2  s  . c o m
    TypedQuery<Long> q = em.createQuery(cq);
    return q.getSingleResult();
}

From source file:com.expedia.seiso.domain.service.search.QueryFactory.java

public Query buildQuery(@NotEmpty String entityName, @NotNull EntityManager entityManager,
        @NotNull Set<String> fieldNames, @NotNull Set<String> searchTokens) {
    Query jpaQuery = null;/*from  w w  w.  j  av a  2  s .c om*/

    Assert.notEmpty(fieldNames, "empty field names");
    Assert.notEmpty(searchTokens, "empty search tokens");

    StringBuilder queryStringBuilder = new StringBuilder();

    List<String> parameterNames = this.appendQueryString(queryStringBuilder, entityName, fieldNames,
            searchTokens);
    jpaQuery = entityManager.createQuery(queryStringBuilder.toString());
    this.setParameters(jpaQuery, parameterNames, searchTokens);

    return jpaQuery;
}

From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java

public List<T> find(final String queryStr, final Object[] params, final int begin, final int max) {
    List<T> ret = (List<T>) this.getJpaTemplate().execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {

            String clazzName = clazz.getName();
            StringBuffer sb = new StringBuffer("select obj from ");
            sb.append(clazzName).append(" obj").append(" where ").append(queryStr);
            Query query = em.createQuery(sb.toString());
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }/*from   w  w w. j  a  va 2  s .  c  om*/
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList<T>();
    }
}

From source file:BO.UserHandler.java

public List<VUser> getPendingFriends(VUser user) {

    EntityManager em;

    EntityManagerFactory emf;//  w  ww .j a  v a 2s  .c  o m
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        List<Friendship> list = (List<Friendship>) em
                .createQuery("SELECT f FROM Friendship f WHERE f.receivingFriend.email LIKE :email "
                        + "AND f.didRespond LIKE :didrespond")
                .setParameter("email", user.getEmail()).setParameter("didrespond", false).getResultList();

        List<VUser> senders = new ArrayList<>();

        for (Friendship f : list) {
            senders.add(new VUser(f.getSendingFriend().getEmail(), "", "", "", false));
        }
        return senders;
    } catch (Exception e) {
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:BO.UserHandler.java

public List<VUser> getFriends(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;/*from   w  ww.j  a v a 2s . c  o  m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        List<Friendship> list = (List<Friendship>) em
                .createQuery("SELECT f FROM Friendship f WHERE f.receivingFriend.email LIKE :email "
                        + "OR f.sendingFriend.email LIKE :email2")
                .setParameter("email", user.getEmail()).setParameter("email2", user.getEmail()).getResultList();

        List<VUser> friends = new ArrayList<>();

        for (Friendship f : list) {
            if (f.isDidAccept()) {
                if (f.getSendingFriend().getEmail().equals(user.getEmail())) {
                    friends.add(new VUser(f.getReceivingFriend().getEmail(), "", "", "", false));
                } else {
                    friends.add(new VUser(f.getSendingFriend().getEmail(), "", "", "", false));
                }
            }
        }

        return friends;
    } catch (Exception e) {
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:de.egore911.persistence.selector.AbstractSelector.java

private TypedQuery<T> buildQuery() {
    EntityManager em = EntityManagerUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(getEntityClass());
    Root<T> from = cq.from(getEntityClass());
    List<Predicate> predicates = generatePredicateList(builder, from, cq);
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    cq.orderBy(generateOrderList(builder, from));
    cq.select(from);/*from  w w w .  j  a  v a  2  s.  c  o  m*/
    return em.createQuery(cq);
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count all entity//from w  w  w  .  j a  v a  2s. c o  m
 *
 * @return
 */
public int count() {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> rt = cq.from(entityClass);
    cq.select(cb.count(rt));
    Query q = em.createQuery(cq);
    Object result = q.getSingleResult();
    return result == null ? 0 : ((Long) result).intValue();
}

From source file:com.carser.viamais.vo.TransactionFilter.java

public Long count(final EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<Transaction> transaction = cq.from(Transaction.class);
    cq.select(cb.countDistinct((transaction)));
    cq.where(getPredicates(cb, transaction));
    return em.createQuery(cq).getSingleResult();
}