/** Test execute method with new entry. */
  @SuppressWarnings("unchecked")
  @Test
  public void testExecute() {
    final long activityId = 6790L;
    final long personId = 99L;

    // verify that entry is not present.
    Query q =
        getEntityManager()
            .createQuery("FROM LikedActivity where personId=:personId and activityId=:activityId")
            .setParameter("personId", personId)
            .setParameter("activityId", activityId);
    List<LikedActivity> results = q.getResultList();
    assertTrue(results.size() == 0);

    String key = CacheKeys.LIKED_BY_PERSON_ID + personId;
    // verify that cached list is empty
    assertTrue(insertLikedActivity.getCache().getList(key) == null);

    // insert it.
    assertTrue(insertLikedActivity.execute(new LikedActivity(personId, activityId)));

    // verify it's there now.
    assertTrue(q.getResultList().size() == 1);

    // verify liked ids by user id is gone.
    assertTrue(insertLikedActivity.getCache().getList(key) == null);
  }
  /** Test native query. */
  public void testNativeQuery() {
    EntityManager em = createEntityManager();

    MappedInteraction interaction = new MappedInteraction();
    interaction.setProperty(OracleNoSQLPlatform.OPERATION, OracleNoSQLOperation.GET.name());
    interaction.addArgumentValue("[Order-mapped," + existingOrder.id + "]", "");
    Query query = em.unwrap(JpaEntityManager.class).createQuery(interaction);
    List result = query.getResultList();
    if ((result.size() != 1)
        || (!(result.get(0) instanceof Record))
        || !(((Record) result.get(0)).containsKey("[Order-mapped," + existingOrder.id + "]"))) {
      fail("Incorrect result: " + result);
    }

    interaction = new MappedInteraction();
    interaction.setProperty(OracleNoSQLPlatform.OPERATION, OracleNoSQLOperation.GET.name());
    interaction.setProperty(OracleNoSQLPlatform.TIMEOUT, "1000");
    interaction.setProperty(OracleNoSQLPlatform.CONSISTENCY, "ABSOLUTE");
    interaction.addArgumentValue("ID", existingOrder.id);
    query = em.unwrap(JpaEntityManager.class).createQuery(interaction, Order.class);
    result = query.getResultList();
    if ((result.size() != 1) || (!(result.get(0) instanceof Order))) {
      fail("Incorrect result: " + result);
    }
  }
Example #3
0
 private boolean userExist(String registerKey, UserType userType) {
   String[] authenticateKeysForLog = {registerKey, userType.name()};
   Logger.getLogger(UsersResource.class.getName())
       .log(
           Level.INFO,
           "######### Check if user exists: registerKey: {0}, userType: {1}.",
           authenticateKeysForLog);
   EntityManager em = emf.createEntityManager();
   if (UserType.MOBILE.equals(userType)) {
     Query queryQ = em.createNamedQuery("User.findByPhoneNumber");
     queryQ.setParameter("phoneNumber", registerKey);
     return !queryQ.getResultList().isEmpty();
   }
   if (UserType.DUDU.equals(userType)) {
     Query queryQ = em.createNamedQuery("User.findByUserId");
     queryQ.setParameter("userId", registerKey);
     return !queryQ.getResultList().isEmpty();
   }
   if (UserType.QQ.equals(userType)) {
     Query queryQ = em.createNamedQuery("User.findByQQ");
     queryQ.setParameter("qq", registerKey);
     return !queryQ.getResultList().isEmpty();
   }
   if (UserType.WEIBO.equals(userType)) {
     Query queryQ = em.createNamedQuery("User.findByWeibo");
     queryQ.setParameter("weibo", registerKey);
     return !queryQ.getResultList().isEmpty();
   }
   if (UserType.EMAIL.equals(userType)) {
     Query queryQ = em.createNamedQuery("User.findByEmail");
     queryQ.setParameter("email", registerKey);
     return !queryQ.getResultList().isEmpty();
   }
   return true;
 }
  @Override
  public void removeEndpoints(CSARID csarId) {
    this.init();
    this.em.getTransaction().begin();

    // FIXME if somebody deletes a csar before some endpoints where added,
    // some exceptions occur

    // get all rest endpoints for the given csarid
    Query queryRestEndpoints =
        this.em.createQuery("SELECT e FROM RESTEndpoint e where e.csarId = :csarId");
    queryRestEndpoints.setParameter("csarId", csarId);
    @SuppressWarnings("unchecked")
    List<RESTEndpoint> restEndpoints = queryRestEndpoints.getResultList();

    // get all wsdl endpoints for the given csarid
    Query queryWsdlEndpoints =
        this.em.createQuery("SELECT e FROM WSDLEndpoint e where e.csarId = :csarId");
    queryWsdlEndpoints.setParameter("csarId", csarId);
    @SuppressWarnings("unchecked")
    List<WSDLEndpoint> wsdlEndpoints = queryWsdlEndpoints.getResultList();

    // remove all found endpoints one by one
    for (RESTEndpoint restEndpoint : restEndpoints) {
      this.em.remove(restEndpoint);
    }

    for (WSDLEndpoint wsdlEndpoint : wsdlEndpoints) {
      this.em.remove(wsdlEndpoint);
    }

    this.em.getTransaction().commit();
  }
 /**
  * Recupera a lista resultante da query informada, tratando o caso de ser uma lista vazia e por
  * conseguinte evitando algum erro antes de retornar para o serviço.
  *
  * @param query - objeto Query que contem resultado da consulta.
  * @return a lista resultante ou uma lista vazia, caso nenhum dado seja retornado.
  */
 @SuppressWarnings("unchecked")
 protected List<E> getResultList(Query query) {
   if (query.getResultList().isEmpty()) {
     return new ArrayList<E>(0);
   }
   return (List<E>) query.getResultList();
 }
 public SitemapData fetchSitemapData() {
   final Query userQuery = query("select u.id from UserImpl u where u.name<>'googlebot'");
   final Query workoutQuery = query("select w.id from WorkoutImpl w");
   final Query groupQuery = query("select g.id from GroupImpl g");
   return new SitemapData(
       userQuery.getResultList(), workoutQuery.getResultList(), groupQuery.getResultList());
 }
Example #7
0
  public void queryMedicalHistory4() {
    EntityManager em = emf.createEntityManager();
    Map medicals = new HashMap();
    long ssn = 0;
    EntityTransaction tran = em.getTransaction();
    tran.begin();
    String jpql = "select m from MedicalHistory2 m";
    Query q = em.createQuery(jpql);
    List<MedicalHistory2> ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      ssn = m.getId();
    }
    tran.commit();
    em.close();

    em = emf.createEntityManager();
    tran = em.getTransaction();
    tran.begin();
    jpql = "select m from MedicalHistory2 m where m.patient.ssn = " + ssn;
    q = em.createQuery(jpql);
    ms = q.getResultList();
    for (MedicalHistory2 m : ms) {
      assertMedicalHistory2(m);
    }
    tran.commit();
    em.close();

    findObj4(ssn);
  }
Example #8
0
  public Page<Object[]> getCustomerConsist(String type, int pageNo, int pageSize) {

    String hql =
        "select count(id) from Customer c "
            + "where c."
            + type
            + " is not null "
            + "group by c."
            + type;

    Query query = entityManager.createQuery(hql);
    int total = query.getResultList().size();

    hql =
        "select c."
            + type
            + " , count(id) from Customer c where c."
            + type
            + " is not null "
            + "group by c."
            + type;
    query = entityManager.createQuery(hql);
    query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize);
    List content = query.getResultList();

    PageRequest pageable = new PageRequest(pageNo - 1, pageSize);

    PageImpl<Object[]> page = new PageImpl<Object[]>(content, pageable, total);

    return page;
  }
Example #9
0
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    EntityManager em = emProvider.get();

    // obtain a cached finder descriptor (or create a new one)
    JpaFinderProxy.FinderDescriptor finderDescriptor = getFinderDescriptor(methodInvocation);

    Object result = null;

    // execute as query (named params or otherwise)
    Query jpaQuery = finderDescriptor.createQuery(em);
    if (finderDescriptor.isBindAsRawParameters) {
      bindQueryRawParameters(jpaQuery, finderDescriptor, methodInvocation.getArguments());
    } else {
      bindQueryNamedParameters(jpaQuery, finderDescriptor, methodInvocation.getArguments());
    }

    // depending upon return type, decorate or return the result as is
    if (JpaFinderProxy.ReturnType.PLAIN.equals(finderDescriptor.returnType)) {
      result = jpaQuery.getSingleResult();
    } else if (JpaFinderProxy.ReturnType.COLLECTION.equals(finderDescriptor.returnType)) {
      result = getAsCollection(finderDescriptor, jpaQuery.getResultList());
    } else if (JpaFinderProxy.ReturnType.ARRAY.equals(finderDescriptor.returnType)) {
      result = jpaQuery.getResultList().toArray();
    }

    return result;
  }
  /** Test case glassfish issue 2497: */
  public void complexCountOnJoinedVariableSimplePK() {
    oracle.toplink.essentials.ejb.cmp3.EntityManager em =
        (oracle.toplink.essentials.ejb.cmp3.EntityManager) createEntityManager();

    // Need to create the expected result manually, because using the
    // TopLink query API would run into the same issue 2497.
    List expectedResult =
        Arrays.asList(
            new Long[] {
              Long.valueOf(1), Long.valueOf(0),
              Long.valueOf(0), Long.valueOf(1)
            });
    Collections.sort(expectedResult);

    String jpql = "SELECT COUNT(o) FROM Customer c LEFT JOIN c.orders o GROUP BY c.name";
    Query q = em.createQuery(jpql);
    List result = (List) q.getResultList();
    Collections.sort(result);

    Assert.assertEquals("Complex COUNT on joined variable simple PK", expectedResult, result);

    jpql = "SELECT COUNT(DISTINCT o) FROM Customer c LEFT JOIN c.orders o GROUP BY c.name";
    q = em.createQuery(jpql);
    result = (List) q.getResultList();
    Collections.sort(result);

    Assert.assertEquals(
        "Complex COUNT DISTINCT on joined variable simple PK", expectedResult, result);
  }
  /** Test case glassfish issue 2497: */
  public void complexCountOnJoinedVariableCompositePK() {
    oracle.toplink.essentials.ejb.cmp3.EntityManager em =
        (oracle.toplink.essentials.ejb.cmp3.EntityManager) createEntityManager();

    // Need to create the expected result manually, because using the
    // TopLink query API would run into the same issue 2497.
    List expectedResult =
        Arrays.asList(new Long[] {Long.valueOf(2), Long.valueOf(5), Long.valueOf(3)});
    Collections.sort(expectedResult);

    String jpql =
        "SELECT COUNT(p) FROM Employee e LEFT JOIN e.phoneNumbers p WHERE e.lastName LIKE 'S%' GROUP BY e.lastName";
    Query q = em.createQuery(jpql);
    List result = (List) q.getResultList();
    Collections.sort(result);

    Assert.assertEquals(
        "Complex COUNT on outer joined variable composite PK", expectedResult, result);

    // COUNT DISTINCT with inner join
    jpql =
        "SELECT COUNT(DISTINCT p) FROM Employee e JOIN e.phoneNumbers p WHERE e.lastName LIKE 'S%' GROUP BY e.lastName";
    q = em.createQuery(jpql);
    result = (List) q.getResultList();
    Collections.sort(result);

    Assert.assertEquals(
        "Complex DISTINCT COUNT on inner joined variable composite PK", expectedResult, result);
  }
Example #12
0
  public List<Experiment> getSharedExperiments(User user) {
    String queryString = "from User u inner join fetch u.experiments where u.username=:username";
    Query query = dao.getEntityManager().createQuery(queryString);
    query.setParameter("username", user.getUsername());
    @SuppressWarnings("unchecked")
    List<User> users = query.getResultList();
    List<Experiment> experiments = new ArrayList<Experiment>();
    for (User userSingleE : users) {
      Object[] userExperiments = userSingleE.getExperiments().toArray();
      for (Object o : userExperiments) {
        Experiment e = (Experiment) o;
        boolean have = false;
        for (Experiment currentE : experiments) {
          if (currentE.getId() == e.getId()) have = true;
        }
        if (!have) experiments.add(e);
      }
    }

    // get experiments shared with all
    queryString = "from Experiment where shareWithAll=:shareWithAll";
    query = dao.getEntityManager().createQuery(queryString);
    query.setParameter("shareWithAll", true);
    @SuppressWarnings("unchecked")
    List<Object> experimentsSharedWithAll = query.getResultList();
    for (Object o : experimentsSharedWithAll) {
      experiments.add((Experiment) o);
    }

    for (Experiment experiment : experiments) {
      experiment.setNumDataSets(getNumDataSets(experiment));
    }

    return experiments;
  }
  private Element crearEstructuraXML() {

    Element historialNotas = new Element(ConstantesArchivosXML.SUPERPADRE);
    Query q = entityManager.createQuery(ConsultasJpql.HISTORIAL_NOTAS_ESTUDIANTES);
    @SuppressWarnings("unchecked")
    List<Usuario> usuarios = (List<Usuario>) q.getResultList();
    for (Usuario usuario : usuarios) {
      Element usuarioXML = crearXMLUsuario(usuario);
      Query q2 = entityManager.createQuery(ConsultasJpql.HISTORIAL_NOTAS);
      q2.setParameter("parametro", usuario.getId());
      @SuppressWarnings("unchecked")
      List<HistorialNotas> notasCurso = (List<HistorialNotas>) q2.getResultList();
      for (HistorialNotas curso : notasCurso) {
        Element cursoXML =
            crearXMLCurso(
                curso.getGrupoCurso().getCursoGrupo(),
                curso.getNota(),
                curso.getGrupoCurso().getIdGrupo(),
                curso.getGrupoCurso().getSemestre());
        usuarioXML.addContent(cursoXML);
      }
      historialNotas.addContent(usuarioXML);
    }
    return historialNotas;
  }
Example #14
0
  public List<Paquete> consultarPaquetesConfirmadosXRol(Usuariosede Registro) {
    List<Paquete> Resultado = null;
    Query consulta;
    // caso multirol o sede
    if (Registro.getIdrol().getIdrol().toString().compareTo("5") == 0
        || Registro.getIdrol().getIdrol().toString().compareTo("2") == 0) {
      consulta =
          em.createNamedQuery("Seguimiento.findPaqueteByRolSede")
              .setParameter("idsed", Registro.getIdsed());
      Resultado = consulta.getResultList();
    }
    // caso area
    if (Registro.getIdrol().getIdrol().toString().compareTo("1") == 0) {
      consulta =
          em.createNamedQuery("Seguimiento.findPaqueteByArea")
              .setParameter("idsed", Registro.getIdsed());
      Resultado = consulta.getResultList();
    }
    // caso emisario
    if (Registro.getIdrol().getIdrol().toString().compareTo("3") == 0) {
      consulta =
          em.createNamedQuery("Seguimiento.findPaqueteByEmisario")
              .setParameter("idsed", Registro.getIdsed());
      Resultado = consulta.getResultList();
    }

    return Resultado;
  }
  public List<Sesion> getSesionByEstudiante(String matricula) {
    Query query = em.createNamedQuery("Registro.findSesionbyEstu");
    query.setParameter("estudiante", matricula);

    if (query.getResultList() != null) return query.getResultList();
    else return null;
  }
 /**
  * Recupera o objeto da consulta realizada, tratando o caso de não existir nenhum registro e por
  * conseguinte evitando algum erro antes de retornar para o serviço.
  *
  * @param query - objeto Query que contem resultado da consulta.
  * @return o objeto resultante ou <code>null</code>, caso nenhum registro seja encontrado. Caso
  *     seja retornado mais de um registro, então retornada a primeira ocorrência.
  */
 @SuppressWarnings("unchecked")
 protected E getSingleResult(Query query) {
   if (query.getResultList().isEmpty()) {
     return null;
   }
   return (E) query.getResultList().get(0);
 }
 public StatisticsPageData fetchStatisticsPageData(final Long userId, final String discipline)
     throws UserNotFoundException {
   final User user = fetchUser(userId);
   final String fromWhereClause =
       " from WorkoutImpl w where :user MEMBER OF w.participants "
           + (discipline != null ? " and discipline = :discipline " : " ");
   final Query disciplineQuery =
       query(
           "select w.discipline, count(*) from WorkoutImpl w "
               + "WHERE :user MEMBER OF w.participants GROUP BY w.discipline ORDER BY count(*) DESC");
   disciplineQuery.setParameter("user", user);
   final Query query = query("select sum(w.distance) " + fromWhereClause);
   bindQuery(query, user, discipline);
   final Query query2 =
       query(
           "select year(w.date), sum(w.distance), sum(w.duration), sum(w.energy) "
               + fromWhereClause
               + " GROUP BY year(w.date) ORDER BY year(w.date) DESC");
   bindQuery(query2, user, discipline);
   final Query query3 =
       query(
           "select year(w.date), month(w.date), sum(w.distance), sum(w.duration), sum(w.energy) "
               + fromWhereClause
               + "GROUP BY year(w.date), month(w.date) "
               + "ORDER BY year(w.date)  DESC, month(w.date)  DESC");
   bindQuery(query3, user, discipline);
   return new StatisticsPageData(
       user,
       disciplineQuery.getResultList(),
       query.getSingleResult(),
       query2.getResultList(),
       query3.getResultList());
 }
Example #18
0
  @SuppressWarnings("unchecked")
  public List<ReportTask> findTODOTasks() {
    String sql =
        "select * from report_tasks where status in ('%s', '%s') and ( gen_count IS NULL or gen_count <= %d )";
    sql = String.format(sql, Status.planned, Status.inprogress, MAX_GENERATION_COUNT);
    Query query = manager.createNativeQuery(sql, ReportTask.class);
    query.setHint(QueryHints.HINT_CACHE_MODE, CacheMode.IGNORE);
    List<?> result = query.getResultList();
    List<ReportTask> tasks = (List<ReportTask>) result;

    StringBuffer idSbs = new StringBuffer();
    // fill project identifier
    if (!tasks.isEmpty()) {
      List<Long> pId = new ArrayList<Long>();
      for (ReportTask task : tasks) {
        pId.add(task.getProjectId());
      }
      Map<Long, String> projects = new HashMap<Long, String>();
      sql = "select id, name from projects where id in ( %s )";
      query = manager.createNativeQuery(String.format(sql, StringUtils.join(pId, ',')));
      query.setHint(QueryHints.HINT_CACHE_MODE, CacheMode.IGNORE);
      result = query.getResultList();
      for (Object o : result) {
        Object[] objs = (Object[]) o;
        projects.put(((Number) objs[0]).longValue(), objs[1].toString());
      }
      for (ReportTask t : tasks) {
        t.setProjectName(projects.get(t.getProjectId()));
        idSbs.append(t.getId().toString()).append(",");
      }
    }

    logger.info("Find " + tasks.size() + " tasks! :: " + idSbs);
    return tasks;
  }
  @Test(enabled = TESTS_ENABLED)
  @SuppressWarnings("unchecked")
  public void synchronizeRepo() throws Exception {

    // Test
    // --------------------------------------------
    boolean completed =
        pluginService.getContentProviderManager().synchronizeRepo(repoToSync.getId());
    assert completed;

    // Verify
    // --------------------------------------------

    // Make sure the proper calls were made into the provider
    assert contentProvider1.getLogSynchronizePackagesRepos().size() == 1
        : "Expected: 1, Found: " + contentProvider1.getLogSynchronizePackagesRepos().size();

    // Need to add in distro packages being syncced
    assert contentProvider1.getLogGetInputStreamLocations().size()
            == TestContentProvider.PACKAGE_COUNT_FOR_BITS
        : "Expected: "
            + TestContentProvider.PACKAGE_COUNT_FOR_BITS
            + ", Found: "
            + contentProvider1.getLogGetInputStreamLocations().size();

    // Make sure all of the packages were added
    TransactionManager tx = getTransactionManager();
    tx.begin();
    EntityManager entityManager = getEntityManager();

    Query query = entityManager.createNamedQuery(PackageVersion.QUERY_FIND_BY_REPO_ID);
    query.setParameter("repoId", repoToSync.getId());
    List<PackageVersion> repoPackages = query.getResultList();

    assert repoPackages.size() == TestContentProvider.PACKAGES.size()
        : "Expected: " + TestContentProvider.PACKAGES.size() + ", Found: " + repoPackages.size();

    // Make sure all of the distributions were added
    query = entityManager.createNamedQuery(RepoDistribution.QUERY_FIND_BY_REPO_ID);
    query.setParameter("repoId", repoToSync.getId());
    List<RepoDistribution> repoDistributions = query.getResultList();

    assert repoDistributions.size() == TestContentProvider.DISTRIBUTIONS.size()
        : "Expected: "
            + TestContentProvider.DISTRIBUTIONS.size()
            + ", Found: "
            + repoDistributions.size();

    // Make sure each distribution has the correct files associated
    int distro1FileCount =
        countDistroFiles(entityManager, TestContentProvider.DISTRIBUTION_1_LABEL);
    assert distro1FileCount == 2 : "Expected: 2, Found: " + distro1FileCount;

    int distro2FileCount =
        countDistroFiles(entityManager, TestContentProvider.DISTRIBUTION_2_LABEL);
    assert distro2FileCount == 1 : "Expected: 1, Found: " + distro1FileCount;

    tx.rollback();
  }
Example #20
0
 @Override
 public Teacher find(String teacherId) {
   Query query =
       entityManager.createQuery("select u from Teacher u where u.teacherId = :teacherId");
   query.setParameter("teacherId", teacherId);
   if (query.getResultList().size() > 0) return (Teacher) query.getResultList().get(0);
   else return null;
 }
  @Test
  public void shouldExecuteCaseQueries() throws Exception {

    Book25 book01 =
        new Book25(
            "The Hitchhiker's Guide to the Galaxy",
            12F,
            "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.",
            "1-84023-742-2",
            354,
            false,
            "Apress");
    Book25 book02 =
        new Book25("Java EE 6", 50F, "Learn about EE 6", "2-84023-742-2", 450, true, "Apress");
    Book25 book03 =
        new Book25(
            "Narcisse and Golmund",
            10F,
            "One of the best Herman Hesse book",
            "3-84023-742-2",
            153,
            false,
            "Pinguin");

    // Persist the object
    tx.begin();
    em.persist(book01);
    em.persist(book02);
    em.persist(book03);
    tx.commit();

    Query query = em.createQuery("select b.price from Book25 b order by b.isbn");
    List<Float> prices = query.getResultList();
    assertEquals(3, prices.size());
    assertEquals(new Float(12F), prices.get(0));
    assertEquals(new Float(50F), prices.get(1));
    assertEquals(new Float(10F), prices.get(2));

    // TODO should work but not with Derby
    // TODO query = em.createQuery("SELECT CASE b.editor WHEN 'Apress' THEN b.price * 0.5 ELSE
    // b.price * 0.8 END FROM Book25 b ORDER BY b.isbn ASC");

    query =
        em.createQuery(
            "SELECT CASE WHEN b.editor ='Apress' THEN b.price * 0.5 ELSE b.price * 0.8 END FROM Book25 b ORDER BY b.isbn ASC");
    prices = query.getResultList();
    assertEquals(3, prices.size());
    assertEquals("12 * 0.5 = 6", new Double(6), prices.get(0));
    assertEquals("50 * 0.5 = 25", new Double(25), prices.get(1));
    assertEquals("10 * 0.8 = 8", new Double(8), prices.get(2));

    // Remove objects
    tx.begin();
    em.remove(book01);
    em.remove(book02);
    em.remove(book03);
    tx.commit();
  }
 @Transactional
 public Role getRoleByName(String name) {
   Query query =
       getEntityManager()
           .createQuery("select r from Role r where roleName =:roleName", Role.class);
   query.setParameter("roleName", name);
   return (query.getResultList() != null && query.getResultList().size() > 0)
       ? (Role) query.getResultList().get(0)
       : null;
 }
Example #23
0
  @Override
  public List<FlightEntity> getAllFlights() {
    System.err.println("开始getAll Flights method ()");
    Query q = em.createQuery("SELECT a FROM FlightEntity a WHERE a.aircraft IS NULL");
    System.err.println("结束 getAll Flights method ()");
    System.err.println("...." + (List<FlightEntity>) q.getResultList());

    System.err.println("");
    return (List<FlightEntity>) q.getResultList();
  }
  public IpdAppointmentTO inpatientEnquiry(String patientUsername) throws Exception {
    EntityManagerFactory emf = null;
    EntityManager em = null;
    List<IpdAppointmentEntity> l = new ArrayList<IpdAppointmentEntity>();
    try {
      IpdAppointmentTO iat = new IpdAppointmentTO();
      emf = Persistence.createEntityManagerFactory("Post_project");
      em = emf.createEntityManager();
      IpdAppointmentEntity ipd = new IpdAppointmentEntity();
      EntityTransaction et = em.getTransaction();

      Query query1 =
          em.createQuery(
              "select p from IpdAppointmentEntity p where p.username=?1 and p.admissionStatus=?2");
      query1.setParameter(1, patientUsername);
      query1.setParameter(2, "A");

      l = query1.getResultList();
      Iterator i = l.iterator();
      if (l.size() != 0) {
        while (i.hasNext()) {
          ipd = (IpdAppointmentEntity) i.next();
        }
        iat.setDepartment(ipd.getDepartment());
        iat.setBedNo(ipd.getBedNo());
        iat.setRegistrationNo(ipd.getRegistrationNo());
        iat.setDoctorId(ipd.getDoctorId());
        iat.setWardNo(ipd.getWardNo());
        iat.setDateOfAdmission(ipd.getDateOfAdmission());
        iat.setReasonForAdmission(ipd.getReasonForAdmission());
      } else {
        return null;
      }
      EmployeeEntity ee = new EmployeeEntity();
      et.begin();
      Query query2 = em.createQuery("select e from EmployeeEntity e where e.userName=?1");
      query2.setParameter(1, iat.getDoctorId());
      List l1 = query2.getResultList();
      et.commit();
      Iterator i1 = l1.iterator();
      while (i1.hasNext()) {
        ee = (EmployeeEntity) i1.next();
      }

      iat.setDoctorName(ee.getEmployeeName());
      return iat;
    } catch (Exception e) {
      ErrorLogger.logError(this.getClass().getName(), "InpatientEnquiry", e.getMessage());
      throw e;
    } finally {
      if (em != null) {
        em.close();
      }
    }
  }
 // Make calc:
 public Double Calculator(Double amount, String fromCurrency, String toCurrency) {
   Double from;
   Double to;
   Query query = em.createQuery("SELECT c currCode FROM Currency c");
   query.setParameter("currCode", Double.parseDouble(fromCurrency));
   from = (Double) query.getResultList().get(0);
   query.setParameter("currCode", Double.parseDouble(toCurrency));
   to = (Double) query.getResultList().get(0);
   Double exchangeRate = from / to;
   return exchangeRate * amount;
 }
Example #26
0
  /** Preload all lanes and vehicles once. */
  @PostConstruct
  public void init() {
    System.out.println("Initializing MovementsDAOImpl");
    Query laneQuery = em.createQuery("select x from Lane x");
    lanes = laneQuery.getResultList();

    Query vehicleQuery = em.createQuery("select x from Vehicle x");
    vehicles = vehicleQuery.getResultList();

    generateLicensePlates(LICENSES);
  }
Example #27
0
  private void buttonLoginActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_buttonLoginActionPerformed
    boolean verify = false;
    String userName = usernameTextBox.getText();
    String passwd = passwordTextBox.getText();
    if (userName.equals("") && passwd.equals("")) {
      JOptionPane.showMessageDialog(
          AdminLogin.this, "Sorry! You must enter a Username and Password to login ");
      usernameTextBox.requestFocus();
    } else if (passwd.equals("")) {
      JOptionPane.showMessageDialog(AdminLogin.this, "Sorry! You must enter a Password to login ");
      usernameTextBox.requestFocus();
    } else if (userName.equals("")) {
      JOptionPane.showMessageDialog(AdminLogin.this, "Sorry! You must enter a Username to login ");
      usernameTextBox.requestFocus();
    } else {
      System.out.println("check: admin login success");
      Query query = null;
      //		EntityManagerFactory emf = Persistence.createEntityManagerFactory("smsPU");
      //		EntityManager em = emf.createEntityManager();

      query =
          School.manager
              .createQuery(
                  "select a from Administrator a where a.userName = :userName AND a.password = :password")
              .setParameter("userName", userName)
              .setParameter("password", passwd);
      System.out.println("Number of admins is/are : " + query.getResultList().size());
      verify = (query.getResultList().size() == 1) ? true : false;
      //		verify = (passwd.equals(admin.getPassword()) && userName.equals(admin.getUserName())) ?
      // true : false;
      if (verify) {

        Administrator admin = (Administrator) query.getSingleResult();
        this.dispose();
        AdminMainView adminView = new AdminMainView();
        adminView.btnEnabled();
        adminView.setVisible(true);
      } else {
        JOptionPane.showMessageDialog(
            AdminLogin.this, "Access Denied! Invalid Username or Password");
        usernameTextBox.setText("");
        passwordTextBox.setText("");
        usernameTextBox.requestFocus();
      }
      //            } catch (SQLException e) {
      //                System.out.println(e.getMessage());
      //            }

      // TODO add your handling code here:
    }
  } // GEN-LAST:event_buttonLoginActionPerformed
Example #28
0
 @SuppressWarnings("unchecked")
 public static List<Tresources> findMenu(Integer roleid) {
   Query query =
       entityManager()
           .createNativeQuery(
               "SELECT t.* FROM Tresources t INNER JOIN tresources_roles tr on t.id= tr.RESOID  WHERE tr.ROLEID= ? ",
               Tresources.class);
   query.setParameter(1, roleid);
   if (query.getResultList().size() == 0) {
     return null;
   }
   return query.getResultList();
 }
Example #29
0
  @Before
  static void globals() {

    String login = Security.connected();
    boolean connected = false;
    if (login != null && !login.equals("")) {
      connected = true;
      boolean isEmploye = false;

      Object o = Utilisateur.getUserByUsername(login);
      Utilisateur user;
      if (o instanceof Employe) {
        isEmploye = true;
        user = (Employe) o;
      } else {
        user = (Client) o;
      }
      renderArgs.put("isEmploye", isEmploye);
      renderArgs.put("prenom", user.prenom);
      renderArgs.put("nom", user.nom);
      renderArgs.put("id", user.id);
      renderArgs.put("connected", connected);

      // Variables de session
      session.put("user_id", user.id);
      session.put("username", user.username);
      session.put("isEmploye", isEmploye);

      // Récupération du nombre de produit dans le panier
      if (isEmploye == false) {
        Query query2 =
            JPA.em()
                .createQuery(
                    "select p from Panier p where p.panier_en_cours = 1 and p.client = " + user.id);
        List<Panier> PaniersClientUpdated = query2.getResultList();
        if (PaniersClientUpdated.size() > 0) {
          Panier PanierEnCours = PaniersClientUpdated.get(0);
          Query query3 =
              JPA.em()
                  .createQuery(
                      "select p from PanierContenu p where p.panier = " + PanierEnCours.id);
          List<PanierContenu> ContenuDuPanierEnCours = query3.getResultList();
          int NombreProduitsPanier = ContenuDuPanierEnCours.size();
          renderArgs.put("NombreProduitsPanier", NombreProduitsPanier);
        } else {
          int NombreProduitsPanier = 0;
          renderArgs.put("NombreProduitsPanier", NombreProduitsPanier);
        }
      }
    }
  }
Example #30
0
 public List<Object> leerTodo(EntityManager em) {
   List<Object> arreglo = null;
   Query q = em.createQuery("SELECT u FROM Envio u");
   try {
     arreglo = (List<Object>) q.getResultList();
   } catch (NonUniqueResultException e) {
     arreglo = (List<Object>) q.getResultList().get(0);
   } catch (NoResultException e) {
     arreglo = null;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return arreglo;
 }