예제 #1
1
 public void deleteNotValidatedUser(String _username) throws MSMApplicationException {
   NdgUser user = findNdgUserByName(_username);
   if (user != null) {
     try {
       // deleting transactionlog
       Query query = manager.createNamedQuery("transactionlog.findByUser");
       query.setParameter("_user", user);
       Transactionlog t = (Transactionlog) query.getSingleResult();
       manager.remove(t);
       // deleting surveys
       query = manager.createNamedQuery("survey.findByUser");
       query.setParameter("_user", user);
       ArrayList<Survey> surveysListDB = (ArrayList<Survey>) query.getResultList();
       for (Survey survey : surveysListDB) {
         manager.remove(survey);
       }
       // deleting user
       manager.remove(user);
     } catch (NoResultException e) {
       System.err.println(e.getMessage());
     }
   } else {
     throw new UserNotFoundException();
   }
 }
예제 #2
0
  //    //Returns all the electives proposed by students and teachears!
  //    @Override
  //    public Collection<ElectiveDTO> getProposedElectives() {
  //        ArrayList< ElectiveDTO> electiveDTOs = new ArrayList<>();
  //        Query query = entityManager.createNamedQuery("Elective.findAll");
  //        List<Elective> electives = query.getResultList();
  //        for (Elective e : electives) {
  //            if (e.getProposed().equals("0")) {
  //                electiveDTOs.add(new ElectiveDTO(e.getElectiveId(), e.getTitle(),
  // e.getDescription(), e.getCreationDate(), e.getProposed()));
  //            }
  //        }
  //        return electiveDTOs;
  //    }
  // Returns electives that has been approved by the head of program to go for the first round
  @Override
  public Collection<ElectiveFirstDTO> getFirstRndElectives() {

    ArrayList<ElectiveFirstDTO> electiveDTOs = new ArrayList<>();
    Query query = entityManager.createNamedQuery("Elective.findByProposed");
    Query q1, q2;
    query.setParameter("proposed", "1");
    List<Elective> electives = query.getResultList();

    int firstPriorityCount;
    int secondPriorityCount;

    for (Elective e : electives) {
      if (e.getPool() == null) {
        q1 = entityManager.createNamedQuery("FirstRoundVote.count_priority1");
        q1.setParameter("elective", e);
        firstPriorityCount = Integer.parseInt(q1.getSingleResult().toString());

        q2 = entityManager.createNamedQuery("FirstRoundVote.count_priority2");
        q2.setParameter("elective", e);
        secondPriorityCount = Integer.parseInt(q2.getSingleResult().toString());
        electiveDTOs.add(
            new ElectiveFirstDTO(
                e.getElectiveId(),
                e.getTitle(),
                e.getDescription(),
                e.getCreationDate(),
                e.getProposed(),
                firstPriorityCount,
                secondPriorityCount));
      }
    }
    return electiveDTOs;
  }
예제 #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;
 }
예제 #4
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;
  }
  /**
   * test for issue 635: NullPointerException occuring for Object typed version fields. Employee has
   * a write lock (version) field of type Integer The NullPointerException is thrown when comparing
   * versions in ObjectChangeSet#compareWriteLockValues
   */
  public void testCreateEmployeeWithFlush() {
    EntityManager em = createEntityManager("fieldaccess");
    Project project1, project2;
    Employee employee;

    try {
      beginTransaction(em);
      employee = ModelExamples.employeeExample1();
      em.persist(employee);

      // first flush: Employee is written to the database
      Query query = em.createNamedQuery("findFieldAccessProjectByName");
      query.setParameter("name", "Farmer effecency evaluations");
      project1 = (Project) query.getSingleResult();
      employee.getProjects().add(project1);

      // second flush: Employee is modified, but
      // no update to EMPLOYEE table; only join table entry is written
      query = em.createNamedQuery("findFieldAccessProjectByName");
      query.setParameter("name", "Feline Demographics Assesment");
      project2 = (Project) query.getSingleResult();
      employee.getProjects().add(project2);

      // third flush: Employee is modified, but
      // no update to EMPLOYEE table; only join table entry is written
      // A NullPointerException in ObjectChangeSet#compareWriteLockValues
      commitTransaction(em);
    } catch (RuntimeException e) {
      if (isTransactionActive(em)) {
        rollbackTransaction(em);
      }
      closeEntityManager(em);
      throw e;
    }
  }
예제 #6
0
  public Reservation(Adherent _adherent, Ouvrage _ouvrage) {
    this.adherent = _adherent;
    this.ouvrage = _ouvrage;
    this.dateDeReservation = new Date();

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("libraryPU");
    EntityManager em = emf.createEntityManager();

    TypedQuery<Long> countAvailable = em.createNamedQuery("Reservation.countAvailable", Long.class);
    countAvailable.setParameter("work", this.ouvrage);
    Long available = countAvailable.getSingleResult();

    TypedQuery<Long> countReservations =
        em.createNamedQuery("Reservation.countReservations", Long.class);
    countReservations.setParameter("work", this.ouvrage);
    countReservations.setParameter("date", this.dateDeReservation);
    Long reserved = countReservations.getSingleResult();

    if (available > reserved) { // verifier s'il y a encore des items de l'ouvrage disponibles
      // Si oui alors on a jusqu'au soir
      this.dateDExpiration = this.dateDeReservation;
    } else {
      // sinon on changera la valeur dès qu'un item de cet ouvrage rentre
      this.dateDExpiration = null;
    }
  }
예제 #7
0
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/admin", method = RequestMethod.GET)
  public String admin(Model model, HttpSession session, HttpServletResponse response) {

    if (!isLogged(session)) return "redirect:login";

    if (!isAdmin(session)) {
      logout(session);
      return "redirect:login";
    }

    List<Asignatura> asignaturas = null;
    asignaturas =
        (List<Asignatura>) entityManager.createNamedQuery("todasAsignaturas").getResultList();
    model.addAttribute("TodasAsignaturas", asignaturas);
    List<Votacion> votaciones = null;
    votaciones = (List<Votacion>) entityManager.createNamedQuery("todasVotaciones").getResultList();
    model.addAttribute("todasVotaciones", votaciones);
    List<Usuario> usuarios = null;
    usuarios = (List<Usuario>) entityManager.createNamedQuery("todosUsuarios").getResultList();
    model.addAttribute("todosUsuarios", usuarios);
    List<MensajeModeracion> mensajes = null;
    mensajes =
        (List<MensajeModeracion>)
            entityManager.createNamedQuery("todosMensajesModeracion").getResultList();
    model.addAttribute("todosMensajes", mensajes);
    return "admin";
    /**
     * **************poner un boolean para saber si el administrador a leido el mensaje o no y
     * mostrarlo en la tabla**********************
     */
  }
예제 #8
0
 /**
  * Add a new gnome to the customers basket
  *
  * @param username The name of the user
  * @param currentAmount Amount of the new gnome
  * @param currentColor Color of the new gnome
  * @return a updated list with all basket items
  */
 public List<BasketDTO> addToBasket(String username, Integer currentAmount, String currentColor) {
   if (updateInventory(currentColor, currentAmount, false) == true) {
     List<Integer> list =
         em.createNamedQuery("findBasketGnome")
             .setParameter("cus", username)
             .setParameter("col", currentColor)
             .getResultList();
     Integer aprice =
         (Integer)
             em.createNamedQuery("findGnomePrice")
                 .setParameter("col", currentColor)
                 .getSingleResult();
     aprice = aprice * currentAmount;
     BasketDTO basketitem;
     if (!list.isEmpty()) {
       basketitem = em.find(Basket.class, list.get(0));
       basketitem.setAmount(basketitem.getAmount() + currentAmount);
       basketitem.setTotalPrice(basketitem.getTotalPrice() + aprice);
       em.merge(basketitem);
     } else {
       List<Integer> id = em.createNamedQuery("countRows").getResultList();
       if (id.isEmpty()) {
         basketitem = new Basket(username, currentColor, currentAmount, 1, aprice);
       } else {
         int size = id.size();
         size++;
         basketitem = new Basket(username, currentColor, currentAmount, size, aprice);
       }
       em.persist(basketitem);
     }
   }
   return getBasket(username);
 }
 public List findByParameters(String param, Object value, Comparadores comp) {
   /*
   1.Fazer cast do valor do textFile
   2.usar comparador selecionado
   3.Consultar pelo campo escolhido acima
   */
   EntityManager em = null;
   Query consulta = null;
   try {
     em = pbo.getEntityManager();
     switch (param) {
       case "nome":
         consulta =
             em.createNamedQuery("Profissional.findByNome", Profissional.class)
                 .setParameter("nome", "%" + value + "%");
         break;
       case "email":
         consulta =
             em.createNamedQuery("Profissional.findByEmail", Profissional.class)
                 .setParameter("email", "%" + value + "%");
         break;
       default:
         em.createNamedQuery("Profissional.findAll");
         break;
     } // fim switch param
     return consulta.getResultList();
   } catch (Exception ex) {
     Log.log(ProfissionalBO.class.getName(), ex);
   } finally {
     if (em != null) {
       em.close();
     }
   } // fim finally
   return null;
 } // fim find
예제 #10
0
 public List<PontoColeta> buscaPorEmpresaEOuEndereco(Empresa empresa, Endereco endereco) {
   List<PontoColeta> result1 = new ArrayList<PontoColeta>();
   List<PontoColeta> result2 = new ArrayList<PontoColeta>();
   if (empresa != null) {
     result1 =
         em.createNamedQuery("PontoColeta.findByEmpresa")
             .setParameter("idEmpresa", empresa.getIdEmpresa())
             .getResultList();
   }
   if (endereco != null) {
     result2 =
         em.createNamedQuery("PontoColeta.findByEndereco")
             .setParameter("idEndereco", endereco.getIdEndereco())
             .getResultList();
   }
   if (result1.isEmpty() && result2.isEmpty()) return null;
   else if (result1.isEmpty() && (!result2.isEmpty())) return result2;
   else if ((!result1.isEmpty()) && result2.isEmpty()) return result1;
   else {
     for (PontoColeta p : result2) {
       result1.add(p);
     }
     return result1;
   }
 }
예제 #11
0
  @Transactional
  public void recalcularMedias() {
    // Ver las votaciones en las que ha participado el usuario
    List<Votacion> votaciones =
        (List<Votacion>) entityManager.createNamedQuery("todasVotaciones").getResultList();
    for (Votacion i : votaciones) {
      // Buscamos quien es el receptor del mensaje
      long idReceptor = i.getId_receptor();

      // Recalcular las puntuaciones del receptor del mensaje
      Usuario u = null;
      u =
          (Usuario)
              entityManager
                  .createNamedQuery("busquedaUsuarioId")
                  .setParameter("param1", idReceptor)
                  .getSingleResult();
      u.setPuntuacion(
          (Double)
              entityManager
                  .createNamedQuery("puntuacionMedia")
                  .setParameter("param1", idReceptor)
                  .getSingleResult());
      entityManager.persist(u);
    }
  }
예제 #12
0
  @Override
  @Interceptors({CartItemInterceptor.class})
  public CartItemModel addCartItem(String cartUid, String productCode, Integer quantity)
      throws EntityNotFoundException, ModelValidationException {
    LOG.trace("ENTER addCartItem(cartUid, productCode, price, quantity)");
    final CartItemEntity cartItemEntity = new CartItemEntity();
    try {
      // Get Cart Entity
      final TypedQuery<CartModel> cartQuery =
          entityManager.createNamedQuery(CartEntity.QUERY_UUID, CartModel.class);
      cartQuery.setParameter("uuid", UUIDUtils.getIdAsByte(UUIDUtils.fromString(cartUid)));
      final CartModel cart = cartQuery.getSingleResult();

      LOG.debug("cart = {}", cart.toString());

      // Get Product Entity
      final TypedQuery<ProductModel> productQuery =
          entityManager.createNamedQuery(ProductEntity.QUERY_PRODUCT_CODE, ProductModel.class);
      productQuery.setParameter("productCode", productCode);
      final ProductModel productInfo = productQuery.getSingleResult();

      LOG.debug("productInfo = {}", productInfo.toString());

      cartItemEntity.setCart(cart);
      cartItemEntity.setProductInfo(productInfo);
      cartItemEntity.setPrice(productInfo.getProductPrice());
      cartItemEntity.setQuantity(quantity);

      cartItemEJB.persist(cartItemEntity);
      return cartItemEntity;
    } finally {
      LOG.trace("EXIT addCartItem(cartUid, productCode, price, quantity)");
    }
  }
예제 #13
0
 public static UmorzenieN pobierz(EntityManager em, Umorzenie r, String podatnik) {
   UmorzenieN zwrot = null;
   try {
     zwrot =
         (UmorzenieN)
             em.createNamedQuery("UmorzenieN.findStrMcRok")
                 .setParameter("srt", r.getSrodekTrwID())
                 .setParameter("mc", r.getMcUmorzenia())
                 .setParameter("rok", r.getRokUmorzenia())
                 .getSingleResult();
   } catch (Exception e) {
   }
   try {
     if (zwrot == null) {
       zwrot =
           (UmorzenieN)
               em.createNamedQuery("UmorzenieN.findStrNazwaMcRok")
                   .setParameter("srt", r.getNazwaSrodka())
                   .setParameter("podatnik", podatnik)
                   .setParameter("mc", r.getMcUmorzenia())
                   .setParameter("rok", r.getRokUmorzenia())
                   .getSingleResult();
     }
   } catch (Exception e) {
     System.out.println("dziwne");
   }
   return zwrot;
 }
  /** @return */
  private ArrayList<ReferenceDataRefDataType> getUsedRefSpecialtySchemes() {
    System.out.println("\n========> Getting Used specialtyscheme references");

    ArrayList<ReferenceDataRefDataType> refColl = new ArrayList<ReferenceDataRefDataType>();
    Query query = null;
    int startRec = refDetails.getStartingRecNumber();
    int maxDisplay = refDetails.getMaxRecordsToShow();

    if ((refDetails.getLookupSystem().getCodeSystem() == null)
        || (refDetails.getLookupSystem().getCodeSystem().isEmpty())) {
      query = em.createNamedQuery("KMSpecialty.findAllDistinctScheme");
    } else {
      query = em.createNamedQuery("KMSpecialty.findAllDistinctSchemeByWildcard");
      query.setParameter(
          "terminologyScheme", refDetails.getLookupSystem().getCodeSystem().toUpperCase() + "%");
    }
    query.setFirstResult(startRec);
    query.setMaxResults(maxDisplay);
    List<String> foundList = (List<String>) query.getResultList();

    for (int r = 0; r < foundList.size(); r++) {
      ReferenceDataRefDataType aRefData = new ReferenceDataRefDataType();
      aRefData.setId(
          0); // TODO Need to pull the ID for each one of this type from ref_specialty_type
      // ..another call
      aRefData.setName(foundList.get(r));

      refColl.add(aRefData);
    }
    return refColl;
  }
예제 #15
0
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/adminEditAsignatura", method = RequestMethod.POST)
  @Transactional
  public String adminEditAsignatura(
      @RequestParam("source") String formSource,
      @RequestParam("Asignatura") String formAsignatura,
      @RequestParam("Curso") String formCurso,
      @RequestParam("Anio") int formAnio,
      @RequestParam("Id") long formId,
      HttpServletRequest request,
      HttpServletResponse response,
      Model model,
      HttpSession session,
      @RequestParam("csrf") String token) {

    if (!isAdmin(session) || !isTokenValid(session, token))
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    entityManager
        .createNamedQuery("editarAsignatura")
        .setParameter("idParam", formId)
        .setParameter("formAsignatura", formAsignatura)
        .setParameter("formCurso", formCurso)
        .setParameter("formAnio", formAnio)
        .executeUpdate();
    List<Asignatura> asignaturas = null;
    asignaturas =
        (List<Asignatura>) entityManager.createNamedQuery("todasAsignaturas").getResultList();
    model.addAttribute("TodasAsignaturas", asignaturas);
    /*la tabla no se actualiza*/
    /*por alguna razon se queda bloqueado y no sigue ejecutando */
    return "redirect:" + formSource;
  }
예제 #16
0
  @Override
  @Interceptors({CartInterceptor.class})
  @RolesAllowed({"admin", "guest"})
  public CartModel[] getCustomerCarts(String username) throws EntityNotFoundException {
    LOG.trace("ENTER getCustomerCarts(customer)");

    try {
      final TypedQuery<CustomerModel> customerQuery =
          entityManager.createNamedQuery(CustomerEntity.QUERY_USERNAME, CustomerModel.class);
      customerQuery.setParameter("username", username);
      CustomerModel customer = customerQuery.getSingleResult();

      final TypedQuery<CartEntity> customerCartsQuery =
          entityManager.createNamedQuery(CartEntity.QUERY_SELECT_ALL_CUSTOMER, CartEntity.class);
      customerCartsQuery.setParameter("customerInfo", customer);
      final List<CartEntity> resultsList = customerCartsQuery.getResultList();

      if (LOG.isDebugEnabled()) {
        LOG.debug("Result Set Size: {}", resultsList.size());
      }

      final CartModel[] results = new CartModel[resultsList.size()];

      int counter = 0;
      for (final CartModel model : resultsList) results[counter++] = model;

      return results;
    } finally {
      LOG.trace("EXIT getCustomerCarts(customer)");
    }
  }
  @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();
  }
예제 #18
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
      request.getPart("file").write(request.getPart("file").getSubmittedFileName());
      //            out.println("File uploaded successfully! " +
      // request.getPart("file").getSubmittedFileName());
    } catch (Exception e) {
      out.println("Exception -->" + e.getMessage());
    } finally {
    }

    // create a new transaction to add data about the image upload to DB.
    emf = Persistence.createEntityManagerFactory("ImageRektPU");
    em = emf.createEntityManager();
    //        out.println("Still works<br>");
    //        out.println("Transaction created<br>");
    try {
      em.getTransaction().begin();
      //            out.println("Transaction created<br>");
      //            int fileuploader = Integer.parseInt(request.getParameter("fileuploader"));
      //            out.println("User " + request.getParameter("user"));
      User u =
          (User)
              em.createNamedQuery("User.findByUid")
                  .setParameter("uid", Integer.parseInt(request.getParameter("user")))
                  .getSingleResult();
      //            out.println(u.getUname() + "<br>");
      // image title, description, Date generated in java the name of the file
      //            Image img = new Image(request.getParameter("titleinput"),
      // request.getParameter("descriptioninput"), new Date(),
      // request.getPart("file").getSubmittedFileName(), u);
      Image img =
          new Image(
              request.getParameter("titleinput"),
              request.getParameter("descriptioninput"),
              new Date(),
              request.getPart("file").getSubmittedFileName(),
              u);
      //            out.println(img.getTitle() + "<br>");
      em.persist(img);
      em.getTransaction().commit();
      //            out.println("File in DB successfully!");

      emf = Persistence.createEntityManagerFactory("ImageRektPU");
      em = emf.createEntityManager();
      em.getTransaction().begin();
      this.imageList = em.createNamedQuery("Image.findAll").getResultList();
      image = this.imageList.get(this.imageList.size() - 1);
      out.println(image.getIid());
      em.getTransaction().commit();
    } catch (Exception e) {
      out.println("BOOM! " + e);
    }
    emf.close();
  }
예제 #19
0
  /** Test of numOfRetransmits query */
  @Test
  public void test29_numOfRetransmitsQuery() {

    em.getTransaction().begin();
    UserMessage instance = new UserMessage();

    instance.setMessageId(T_MSG_ID_1);
    instance.setProcessingState(new ProcessingState(ProcessingStates.SUBMITTED));
    instance.setProcessingState(new ProcessingState(ProcessingStates.READY_TO_PUSH));
    instance.setProcessingState(new ProcessingState(ProcessingStates.PROCESSING));
    instance.setProcessingState(new ProcessingState(ProcessingStates.AWAITING_RECEIPT));

    em.persist(instance);

    em.getTransaction().commit();

    Long numberOfRetransmits = null;

    try {
      numberOfRetransmits =
          em.createNamedQuery("UserMessage.numOfRetransmits", Long.class)
              .setParameter("msgId", T_MSG_ID_1)
              .getSingleResult();

    } catch (NoResultException nr) {
      fail();
    }

    assertEquals(1, numberOfRetransmits.intValue());

    em.getTransaction().begin();

    instance.setProcessingState(new ProcessingState(ProcessingStates.READY_TO_PUSH));
    instance.setProcessingState(new ProcessingState(ProcessingStates.PROCESSING));
    instance.setProcessingState(new ProcessingState(ProcessingStates.AWAITING_RECEIPT));
    instance.setProcessingState(new ProcessingState(ProcessingStates.READY_TO_PUSH));
    instance.setProcessingState(new ProcessingState(ProcessingStates.PROCESSING));
    instance.setProcessingState(new ProcessingState(ProcessingStates.AWAITING_RECEIPT));

    em.merge(instance);

    em.getTransaction().commit();

    try {
      numberOfRetransmits =
          em.createNamedQuery("UserMessage.numOfRetransmits", Long.class)
              .setParameter("msgId", T_MSG_ID_1)
              .getSingleResult();

    } catch (NoResultException nr) {
      fail();
    }

    assertEquals(3, numberOfRetransmits.intValue());
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    // if a book has been reserved then it cannot be reserved again, cannot be edited and cannot be
    // removed
    // if a book has been returned then it cannot be returned again

    boolean canProceed = false;

    boolean tryingToReturnBook = (request.getParameter("returningBook") != null);

    EntityManager em = PersistenceAdapter.getEntityManager();

    String title = request.getParameter("bookName").trim();
    String author = request.getParameter("authorName").trim();

    Book book =
        (Book)
            em.createNamedQuery("bookByTitleAndAuthor")
                .setParameter("bookName", title)
                .setParameter("authorName", author)
                .getSingleResult();

    try {
      em.createNamedQuery("lendingByBook").setParameter("lendedBook", book).getSingleResult();

      // if the user is trying to return a book and the book has been borrowed then we can proceed
      if (tryingToReturnBook) {
        canProceed = true;
      } else {
        canProceed = false;
      }

    } catch (NoResultException exc) {

      // if the book has not been borrowed and the user is trying to return it, then we cannot
      // proceed
      if (tryingToReturnBook) {
        canProceed = false;
      } else {
        canProceed = true;
      }
    }

    if (canProceed) {
      chain.doFilter(request, response);
    } else {
      JsonObject object = new JsonObject();
      object.addProperty("canProceed", false);
      response.getWriter().print(new Gson().toJson(object));
      ((HttpServletResponse) response).setStatus(400);
      return;
    }
  }
예제 #21
0
 public void deleteBook(int bookId) throws LibraryException {
   BookEntity book = em.find(BookEntity.class, (long) bookId);
   em.createNamedQuery("ReservationEntity.DeleteAllBookReserv")
       .setParameter("bookId", book.getId())
       .executeUpdate();
   em.createNamedQuery("BookCopyEntity.DeleteAllBookCopies")
       .setParameter("bookId", book.getId())
       .executeUpdate();
   em.remove(book);
   // TODO error handling?
 }
예제 #22
0
  @PostConstruct
  private void setupSuggestions() {
    MultiWordSuggestOracle iso = (MultiWordSuggestOracle) name.getSuggestOracle();
    for (Item i : em.createNamedQuery("allItemsByName", Item.class).getResultList()) {
      iso.add(i.getName());
    }

    MultiWordSuggestOracle dso = (MultiWordSuggestOracle) department.getSuggestOracle();
    for (Department d : em.createNamedQuery("allDepartments", Department.class).getResultList()) {
      dso.add(d.getName());
    }
  }
예제 #23
0
  public List<Usuario> editarUsuario(
      int idUsuario,
      String nombreUsuario,
      String paterno,
      String materno,
      String nombre,
      String email,
      int idRol,
      int idSucursal,
      String contrasena,
      String horaEntrada,
      String horaSalida,
      String acceso) {
    try {
      // Inicializamos la transaccion
      em = PersistenceOperation.emf.createEntityManager();
      em.getTransaction().begin();

      TypedQuery<Roles> q = em.createNamedQuery("Roles.findByIdrol", Roles.class);
      q.setParameter("idrol", idRol);
      Roles r = q.getSingleResult();

      TypedQuery<Sucursales> q1 =
          em.createNamedQuery("Sucursales.findByIdsucursal", Sucursales.class);
      q1.setParameter("idsucursal", idSucursal);
      Sucursales s = q1.getSingleResult();

      // Obtenemos usuarios activos;
      TypedQuery<Usuarios> q2 = em.createNamedQuery("Usuarios.findByIdusuario", Usuarios.class);
      q2.setParameter("idusuario", idUsuario);
      Usuarios u = q2.getSingleResult();
      u.setUsuario(nombreUsuario);
      u.setApellidopaterno(paterno);
      u.setApellidomaterno(materno);
      u.setNombre(nombre);
      u.setCorreo(email);
      u.setIdrol(r);
      u.setIdSucursal(s);
      u.setContrasena(contrasena);
      u.setHoraEntrada(horaEntrada);
      u.setHoraSalida(horaSalida);
      u.setAccesoHuella(acceso);
      em.getTransaction().commit();
      em.close();
      return obtenerListaDeUsuarios(idSucursal);
    } catch (java.lang.NumberFormatException ex) {
      return null;
    } catch (Exception ex) {
      return null;
    }
  }
예제 #24
0
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/realizarVotacion", method = RequestMethod.POST) // voto.jsp
  @Transactional
  public String realizarVotacion(
      Model model,
      HttpSession session,
      HttpServletResponse response,
      @RequestParam("comentario") String comentario,
      @RequestParam("csrf") String token) {

    if (!isTokenValid(session, token)) response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    model.addAttribute("prefix", "./");
    long idEmisor = ((Usuario) session.getAttribute("user")).getId();
    long idUsuarioVotacion = Long.parseLong((String) session.getAttribute("usuarioVotacion"));
    ArrayList<Categoria> lista = new ArrayList<Categoria>();
    lista = (ArrayList<Categoria>) session.getAttribute("valoraciones");
    Votacion v = new Votacion();
    v = v.crearVotacion(idEmisor, idUsuarioVotacion, lista, comentario);
    entityManager.persist(v);

    // Recalcular las puntuaciones
    Usuario u = null;
    u =
        (Usuario)
            entityManager
                .createNamedQuery("busquedaUsuarioId")
                .setParameter(
                    "param1", Long.parseLong((String) session.getAttribute("usuarioVotacion")))
                .getSingleResult();
    u.setPuntuacion(
        (Double)
            entityManager
                .createNamedQuery("puntuacionMedia")
                .setParameter(
                    "param1", Long.parseLong((String) session.getAttribute("usuarioVotacion")))
                .getSingleResult());
    entityManager.persist(u);

    // String subconsulta = ("SELECT AVG(V.PUNTUACION) FROM VOTACION WHERE
    // ID_RECEPTOR="+idUsuarioVotacion);
    // String query = "UPDATE USUARIO SET PUNTUACION_MEDIA=(" + subconsulta + ") WHERE ID="
    // +idUsuarioVotacion;
    // Integer puntuacion = (Integer) entityManager.createNativeQuery(query).getFirstResult();
    // u.setPuntuacion(puntuacion);
    // entityManager.createNativeQuery(subconsulta).executeUpdate();

    session.removeAttribute("valoraciones");
    session.removeAttribute("usuarioVotacion");
    return "home";
  }
  @GET
  @Path("count/{id}")
  @Produces("text/plain")
  public String countByPatientId(@PathParam("id") Integer id) {
    Query p = em.createNamedQuery("Patient.findById");
    p.setParameter("id", id);
    Patient patient = (Patient) p.getSingleResult();

    Query q = em.createNamedQuery("PatientHistoryrecord.findByPatient");
    q.setParameter("patient", patient);
    List<PatientHistoryrecord> list = q.getResultList();

    return String.valueOf(list.size());
  }
  @GET
  @Path("patient/{id}")
  @Produces({"application/xml", "application/json"})
  public List<PatientHistoryrecord> findByPatientId(@PathParam("id") Integer id) {
    Query p = em.createNamedQuery("Patient.findById");
    p.setParameter("id", id);
    Patient patient = (Patient) p.getSingleResult();

    Query q = em.createNamedQuery("PatientHistoryrecord.findByPatient");
    q.setParameter("patient", patient);
    List<PatientHistoryrecord> list = q.getResultList();

    return list;
  }
 /**
  * New fields added:[googlePlayStoreId,itunesStoreId,amazonStoreId] API for method:
  * .../rest/premium_package_properties?forPayingUser=VALUE&forNonPayingUser=VALUE This method
  * returns JSON list. Default value for forPayingUser is 0, and for forNonPayingUser is 0. You can
  * put your values for forPayingUser, forNonPayingUser. It produces APPLICATION_JSON media type.
  * Example for JSON list: <br>
  * {<br>
  * "count": 1,<br>
  * "data": [<br>
  * {<br>
  * "createDate": 1427204490000,<br>
  * "redirectUrl": "",<br>
  * "charityDescription": "",<br>
  * "charityDonation": null,<br>
  * "forNonPayingUsers": 0,<br>
  * "forPayingUsers": 0,<br>
  * "highlightImageUrl": "",<br>
  * "showUntil": null,<br>
  * "idFavoriteClub": null,<br>
  * "idPremiumPackageSuccessor": 8,<br>
  * "idPremiumPackageUpgrade": null,<br>
  * "imageUrlSpecial": "",<br>
  * "maxPurchasesPerUser": null,<br>
  * "redirectImageUrl": "",<br>
  * "redirectPositionLeft": null,<br>
  * "redirectPositionTop": null,<br>
  * "updateTimestamp": null,<br>
  * "showOnlySpecial": 0,<br>
  * "showFrom": null,<br>
  * "googlePlayStoreId": null,<br>
  * "itunesStoreId": null,<br>
  * "amazonStoreId": null,<br>
  * "id": 1<br>
  * }<br>
  * }]<br>
  *
  * @param token is a header parameter for checking permission
  * @param request
  * @param forPayingUser - true if you want only premium package properties for paying users
  * @param forNonPayingUser - true if you want only premium package properties for non paying users
  * @return Response 200 OK with JSON body
  * @throws DataNotFoundException DataNotFoundException Example for exception:<br>
  *     {<br>
  *     "errorMessage": "Requested page does not exist..",<br>
  *     "errorCode": 404<br>
  *     }
  */
 @GET // question?page=1&limit=10&minDate=1438387200000&maxDate=1439164800000&search=Viktor&column=id
 @Produces(MediaType.APPLICATION_JSON)
 public Response getPremiumPackageProperties(
     @HeaderParam("authorization") String token,
     @Context HttpServletRequest request,
     @DefaultValue("false") @QueryParam("forPayingUser") boolean forPayingUser,
     @DefaultValue("false") @QueryParam("forNonPayingUser") boolean forNonPayingUser) {
   EntityManager em = helper.getEntityManager();
   CmsActionHistory history =
       helper.checkUserAndPrivileges(
           em,
           TableConstants.SHOP,
           MethodConstants.SEARCH,
           token,
           request.getRequestURL().toString()
               + (request.getQueryString() != null ? "?" + request.getQueryString() : ""),
           null);
   List<PremiumPackageProperties> premiumPackageProperties;
   if (forPayingUser) {
     premiumPackageProperties =
         em.createNamedQuery("PremiumPackageProperties.findByForPayingUsers")
             .setParameter("forPayingUsers", Short.parseShort("1"))
             .getResultList();
   } else {
     if (forNonPayingUser) {
       premiumPackageProperties =
           em.createNamedQuery("PremiumPackageProperties.findByForNonPayingUsers")
               .setParameter("forNonPayingUsers", Short.parseShort("1"))
               .getResultList();
     } else {
       premiumPackageProperties =
           em.createNamedQuery("PremiumPackageProperties.findAll").getResultList();
     }
   }
   if (premiumPackageProperties == null || premiumPackageProperties.isEmpty()) {
     helper.setResponseToHistory(
         history, new DataNotFoundException("Requested page does not exist.."), em);
     throw new DataNotFoundException("Requested page does not exist..");
   }
   String countQuery = "Select COUNT(p) From PremiumPackageProperties p";
   long count = (long) em.createQuery(countQuery).getSingleResult();
   GetObject go = new GetObject();
   go.setCount(count);
   go.setData(
       PremiumPackagePropertiesPOJO.toPremiumPackagePropertiesPOJOList(premiumPackageProperties));
   Response response = Response.ok().entity(go).build();
   helper.setResponseToHistory(history, response, em);
   return response;
 }
  private int countDistroFiles(EntityManager entityManager, String label) {
    Query query = entityManager.createNamedQuery(Distribution.QUERY_FIND_BY_DIST_LABEL);
    query.setParameter("label", label);
    Distribution distro = (Distribution) query.getSingleResult();

    query = entityManager.createNamedQuery(DistributionFile.SELECT_BY_DIST_ID);
    query.setParameter("distId", distro.getId());
    List distroFiles = query.getResultList();

    if (distroFiles == null) {
      return 0;
    } else {
      return distroFiles.size();
    }
  }
 /* (non-Javadoc)
  * @see org.mitre.uma.repository.PermissionRepository#getPermissionTicketsForResourceSet(org.mitre.uma.model.ResourceSet)
  */
 @Override
 public Collection<PermissionTicket> getPermissionTicketsForResourceSet(ResourceSet rs) {
   TypedQuery<PermissionTicket> query =
       em.createNamedQuery(PermissionTicket.QUERY_BY_RESOURCE_SET, PermissionTicket.class);
   query.setParameter(PermissionTicket.PARAM_RESOURCE_SET_ID, rs.getId());
   return query.getResultList();
 }
 /* (non-Javadoc)
  * @see org.mitre.uma.repository.PermissionRepository#getByTicket(java.lang.String)
  */
 @Override
 public PermissionTicket getByTicket(String ticket) {
   TypedQuery<PermissionTicket> query =
       em.createNamedQuery(PermissionTicket.QUERY_TICKET, PermissionTicket.class);
   query.setParameter(PermissionTicket.PARAM_TICKET, ticket);
   return JpaUtil.getSingleResult(query.getResultList());
 }