public void remove(ResourceType type, Object name) {
   EntityManager em = ResourceUtils.getEntityManager();
   em.getTransaction().begin();
   Query q;
   QueryGenerator generator;
   switch (type) {
     case WORKFLOW_DATA:
       generator = new QueryGenerator(WORKFLOW_DATA);
       //                generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID);
       generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name);
       q = generator.deleteQuery(em);
       q.executeUpdate();
       break;
     case EXPERIMENT_METADATA:
       generator = new QueryGenerator(EXPERIMENT_METADATA);
       generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name);
       q = generator.deleteQuery(em);
       q.executeUpdate();
       break;
     case GFAC_JOB_DATA:
       generator = new QueryGenerator(GFAC_JOB_DATA);
       generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name);
       q = generator.deleteQuery(em);
       q.executeUpdate();
       break;
     default:
       break;
   }
   em.getTransaction().commit();
   em.close();
 }
Example #2
0
  /**
   * Deletes a tag.
   *
   * @param tagId Tag ID
   * @param userId User ID
   */
  public void delete(String tagId, String userId) {
    EntityManager em = ThreadLocalContext.get().getEntityManager();

    // Get the tag
    Query q = em.createQuery("select t from Tag t where t.id = :id and t.deleteDate is null");
    q.setParameter("id", tagId);
    Tag tagDb = (Tag) q.getSingleResult();

    // Delete the tag
    Date dateNow = new Date();
    tagDb.setDeleteDate(dateNow);

    // Delete linked data
    q =
        em.createQuery(
            "update DocumentTag dt set dt.deleteDate = :dateNow where dt.tagId = :tagId and dt.deleteDate is not null");
    q.setParameter("dateNow", dateNow);
    q.setParameter("tagId", tagId);
    q.executeUpdate();

    q =
        em.createQuery(
            "update Acl a set a.deleteDate = :dateNow where a.sourceId = :tagId and a.deleteDate is null");
    q.setParameter("tagId", tagId);
    q.setParameter("dateNow", dateNow);
    q.executeUpdate();

    // Create audit log
    AuditLogUtil.create(tagDb, AuditLogType.DELETE, userId);
  }
 protected void deleteTenantHistories(T tenantModel, List<H> tenantHistories) {
   Query q = null;
   for (HistoryTenantModel historyTenant : tenantHistories) {
     q =
         getEntityManager()
             .createQuery(
                 String.format("DELETE FROM %s a WHERE a.id = ?1", getClassName(historyTenant)));
     q.setParameter(1, historyTenant.getId());
     Assert.assertEquals(1, q.executeUpdate());
     q =
         getEntityManager()
             .createQuery(
                 String.format(
                     "DELETE FROM %s ht WHERE ht.id = ?1",
                     getClassName(historyTenant.getAudit())));
     q.setParameter(1, historyTenant.getAudit().getId());
     Assert.assertEquals(1, q.executeUpdate());
   }
   q =
       getEntityManager()
           .createQuery(
               String.format("DELETE FROM %s a WHERE a.id = ?1", getClassName(tenantModel)));
   q.setParameter(1, tenantModel.getId());
   Assert.assertEquals(1, q.executeUpdate());
 }
 public Boolean defineDefault(RelatorioOrdem ro) {
   try {
     getEntityManager().getTransaction().begin();
     Query query =
         getEntityManager()
             .createNativeQuery(
                 "UPDATE sis_relatorio_ordem SET is_default = false WHERE id_relatorio = "
                     + ro.getRelatorios().getId());
     if (query.executeUpdate() == 0) {
       getEntityManager().getTransaction().rollback();
       return false;
     }
     query =
         getEntityManager()
             .createNativeQuery(
                 "UPDATE sis_relatorio_ordem SET is_default = true WHERE id = " + ro.getId());
     if (query.executeUpdate() == 0) {
       getEntityManager().getTransaction().rollback();
       return false;
     }
     getEntityManager().getTransaction().commit();
   } catch (Exception e) {
     getEntityManager().getTransaction().rollback();
     return false;
   }
   return true;
 }
Example #5
0
  @Override
  public void restoreVoteTables() {
    Query query1 = entityManager.createQuery("DELETE * FROM FIRST_ROUND_VOTE");
    Query query2 = entityManager.createQuery("DELETE * FROM SECOND_ROUND_VOTE");

    query1.executeUpdate();
    query2.executeUpdate();
  }
Example #6
0
  @Override
  @Transactional
  public void delete(String uuid) {
    String sql = "delete from KeyValueVO vo where vo.uuid = :uuid";
    Query q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("uuid", uuid);
    q.executeUpdate();

    sql = "delete from KeyValueBinaryVO vo where vo.uuid = :uuid";
    q = dbf.getEntityManager().createQuery(sql);
    q.setParameter("uuid", uuid);
    q.executeUpdate();
  }
Example #7
0
  @PostConstruct
  public void startup() throws Exception {
    Query q = entityManager.createNativeQuery("DELETE from ADDRESS");
    q.executeUpdate();
    q = entityManager.createNativeQuery("DELETE from PERSON");
    q.executeUpdate();
    entityManager.flush();

    p = new Person();
    p.setFirstName("Shane");
    p.setLastName("Bryzak");
    p.setDateOfBirth(df.parse("1901-01-01"));
    p.setAddresses(new ArrayList<Address>());

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(100);
    a.setStreetName("Main");
    a.setSuburb("Pleasantville");
    a.setPostCode("32123");
    a.setCountry("Australia");
    p.getAddresses().add(a);

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(57);
    a.setStreetName("1st Avenue");
    a.setSuburb("Pittsville");
    a.setPostCode("32411");
    a.setCountry("Australia");
    p.getAddresses().add(a);
    entityManager.persist(p);
    entityManager.flush();

    p = new Person();
    p.setFirstName("Jozef");
    p.setLastName("Hartinger");
    p.setDateOfBirth(df.parse("1901-01-01"));
    p.setAddresses(new ArrayList<Address>());

    a = new Address();
    a.setPerson(p);
    a.setStreetNo(99);
    a.setStreetName("Purkynova");
    a.setSuburb("Kralovo pole");
    a.setPostCode("60200");
    a.setCountry("Czech republic");
    p.getAddresses().add(a);
    entityManager.persist(p);
    entityManager.flush();
  }
 @Override
 @RawEventsTransactional
 public int deletePortalEventsBefore(DateTime time) {
   final Query query = this.getEntityManager().createQuery(this.deleteQuery);
   query.setParameter(this.endTimeParameter.getName(), time);
   return query.executeUpdate();
 }
Example #9
0
  @Override
  public void clear() {
    EntityManager em = emf.createEntityManager();
    EntityTransaction txn = em.getTransaction();

    try {
      // the clear operation often deadlocks - let's try several times
      for (int i = 0; ; ++i) {
        txn.begin();
        try {
          log.trace("Clearing JPA Store");
          String entityTable = em.getMetamodel().entity(configuration.entityClass()).getName();
          @SuppressWarnings("unchecked")
          List<Object> items = em.createQuery("FROM " + entityTable).getResultList();
          for (Object o : items) em.remove(o);
          if (configuration.storeMetadata()) {
            String metadataTable = em.getMetamodel().entity(MetadataEntity.class).getName();
            Query clearMetadata = em.createQuery("DELETE FROM " + metadataTable);
            clearMetadata.executeUpdate();
          }
          txn.commit();
          em.clear();
          break;
        } catch (Exception e) {
          log.trace("Failed to clear store", e);
          if (i >= 10) throw new JpaStoreException("Exception caught in clear()", e);
        } finally {
          if (txn != null && txn.isActive()) txn.rollback();
        }
      }
    } finally {
      em.close();
    }
  }
Example #10
0
 public void updateContact(Contact cn, String id) {
   EntityTransaction et = em.getTransaction();
   et.begin();
   Query query = em.createQuery("UPDATE c from Contact c WHERE c.id=" + id);
   query.executeUpdate();
   et.commit();
 }
Example #11
0
 @Override
 public void deleteAll() {
   em.getTransaction().begin();
   Query query = em.createQuery("DELETE FROM OrderModel");
   query.executeUpdate();
   em.getTransaction().commit();
 }
 @Override
 public void execute(Application application) {
   Query query =
       em.createNativeQuery("{call PROC_BORROW_OLD(?)}")
           .setParameter(1, application.getApplicationNo());
   query.executeUpdate();
 }
Example #13
0
  public void testPagingInCollection() throws Exception {
    // create objects in database
    Formula formula = Formula.findByName("HTML TEST");
    Ingredient ingredient = Ingredient.findByName("LECHE");
    for (int x = 0; x <= 12; x++) {
      FormulaIngredient fi = new FormulaIngredient();
      fi.setFormula(formula);
      fi.setIngredient(ingredient);
      XPersistence.getManager().persist(fi);
    }
    XPersistence.commit();

    //
    execute("Mode.detailAndFirst");
    assertValue("name", "HTML TEST");
    assertCollectionRowCount("ingredients", 10);
    checkRowCollection("ingredients", 0);
    execute("List.goNextPage", "collection=ingredients");
    execute("List.goPreviousPage", "collection=ingredients");
    assertRowCollectionChecked("ingredients", 0);

    // remove objects from database
    String sentencia = " DELETE FROM FormulaIngredient WHERE ingredient.oid = :ingredient ";
    Query query = XPersistence.getManager().createQuery(sentencia);
    query.setParameter("ingredient", ingredient.getOid());
    query.executeUpdate();
    XPersistence.commit();
  }
  @Override
  public void deleteAll(Trading trading) {

    final Query query = em.createQuery("DELETE FROM Withdrawal w WHERE w.pk.trading=:trading");
    query.setParameter("trading", trading);
    query.executeUpdate();
  }
Example #15
0
 public int markListAsBilled(List<String> list) { // TODO: Should be set form CONST var
   Query query =
       entityManager.createQuery(
           "UPDATE Billingmaster b set b.billingstatus = 'B' where b.billingmasterNo in (:billingNumbers)");
   query.setParameter("billingNumbers", ConversionUtils.toIntList(list));
   return query.executeUpdate();
 }
Example #16
0
  private void updateProcess(String tableName, Map fieldsAndParams, String wheresql)
      throws DaoException {
    StringBuffer sf_update = new StringBuffer("UPDATE ").append(tableName).append(" o set");
    Object[] params = new Object[fieldsAndParams.size()];
    int index = 0;
    Set entrys = fieldsAndParams.entrySet();
    {
      Iterator it = entrys.iterator();
      while (it.hasNext()) {
        Entry entry = (Entry) it.next();
        sf_update.append(" ").append(entry.getKey()).append("=?,");
        params[index++] = entry.getValue();
      }
    }

    Query query =
        getEntityManager()
            .createQuery(
                sf_update.substring(0, sf_update.length() - 1)
                    + ((wheresql == null) ? "" : (" where " + wheresql)));
    setQueryParams(query, params);
    startTxn();
    query.executeUpdate();
    getEntityManager().getTransaction().commit();
  }
Example #17
0
  @Override
  public int insertCorte(CorteCaja cc) {
    System.out.println("+++++++++++++EJB++++++++++");
    System.out.println(cc.toString());
    Query query =
        em.createNativeQuery(
            "INSERT INTO Corte_Caja(ID_CORTE_CAJA_PK,ID_CAJA_FK,FECHA,CANT_CHEQUES_ANT,"
                + "                         MONTO_CHEQUES_ANT,SALDO_ANTERIOR,CANT_CHEQUES_NUEVOS,MONTO_CHEQUES_NUEVOS,NUEVO_SALDO,"
                + "                         COMENTARIOS,ID_USER_FK,ID_STATUS_FK,MONTO_CUENTA_ANT,MONTO_CUENTA_NUEVO) VALUES(?,?,sysdate,?,?,?,?,?,?,?,?,?,?,?)");

    query.setParameter(1, cc.getIdCorteCajaPk());
    query.setParameter(2, cc.getIdCajaFk());
    query.setParameter(3, cc.getCantChequesAnt());
    query.setParameter(4, cc.getMontoChequesAnt());
    query.setParameter(5, cc.getSaldoAnterior());
    query.setParameter(6, cc.getCantChequesNuevos());
    query.setParameter(7, cc.getMontoChequesNuevos());
    query.setParameter(8, cc.getSaldoNuevo());
    query.setParameter(9, cc.getComentarios());
    query.setParameter(10, cc.getIdUserFk());
    query.setParameter(11, cc.getIdStatusFk());
    query.setParameter(12, cc.getMontoCuentaAnterior());
    query.setParameter(13, cc.getMontoCuentaNuevo());
    return query.executeUpdate();
  }
Example #18
0
  @Override
  @TransactionalPaaS
  public void update(StaffInCharge entity) {
    StringBuilder sb = new StringBuilder();

    sb.append("UPDATE ");
    sb.append(this.getPersistentClass().getName());
    sb.append(" e SET ");
    sb.append("e.workingStartDate = ?, ");
    sb.append("e.workingEndDate = ?, ");
    sb.append("e.clientId = ?, ");
    sb.append("e.staffId = ? ");
    sb.append("WHERE e.staffInChargeId = ?");

    Query q = this.entityManager.createQuery(sb.toString());

    int i = 0;

    q.setParameter(++i, entity.getWorkingStartDat());
    q.setParameter(++i, entity.getWorkingEndDate());
    q.setParameter(++i, entity.getClientId());
    q.setParameter(++i, entity.getStaffId());
    q.setParameter(++i, entity.getStaffInChargeId());

    q.executeUpdate();
  }
 @Override
 @Transactional("transactionManager")
 public void removeByClientId(String orcid) {
   Query query = entityManager.createQuery("delete from ClientDetailsEntity  where id = :orcid");
   query.setParameter("orcid", orcid);
   query.executeUpdate();
 }
Example #20
0
  public void markStaleServersDown(Subject subject) {
    if (!authorizationManager.isOverlord(subject)) {
      throw new IllegalArgumentException(
          "The markStaleServersDown method must be called by the overlord");
    }

    long staleTime = System.currentTimeMillis() - SERVER_DOWN_INTERVAL;

    String serverName = null;
    try {
      serverName = serverManager.getIdentity();
      if (log.isDebugEnabled()) {
        log.debug(serverName + " is marking stale servers DOWN");
      }
    } catch (Exception e) {
      log.error("Could not determine which instance is marking stale servers DOWN");
    }
    Query query = entityManager.createNamedQuery(Server.QUERY_UPDATE_SET_STALE_DOWN);
    query.setParameter("downMode", Server.OperationMode.DOWN);
    query.setParameter("normalMode", Server.OperationMode.NORMAL);
    query.setParameter("staleTime", staleTime);
    query.setParameter("thisServerName", serverName); // might be null
    int resultCount = query.executeUpdate();

    if (log.isDebugEnabled()) {
      log.debug(String.valueOf(resultCount) + " stale servers were marked DOWN");
    }

    // Perform requested partition events. Note that we only need to execute one cloud partition
    // regardless of the number of pending requests, as the work would be duplicated.
    partitionEventManager.processRequestedPartitionEvents();
  }
  @DELETE
  @Path("/{name}")
  @RolesAllowed({"user", "admin"})
  public Response deleteClustering(@PathParam("name") String clusteringName) {

    EntityManager em = Application.createEntityManager();
    Clustering clustering = em.find(Clustering.class, clusteringName);

    if (clustering == null)
      return Response.status(404).entity("Clustering not found for this name.").build();

    try {
      em.getTransaction().begin();
      Query q = em.createQuery("delete from News n where n.clustering.name = :name");
      q.setParameter("name", clusteringName);
      q.executeUpdate();
      em.remove(clustering);
      em.getTransaction().commit();
    } catch (Exception e) {
      em.getTransaction().rollback();
      return Response.status(500).entity(e.getMessage()).build();
    }

    return Response.status(200).build();
  }
 public void deleteMessageFor(final Long id, final User user) {
   final Query query =
       entityManager.createNativeQuery(
           "update MESSAGES SET deleted_by=:user_id where ID=:id and deleted_by IS NULL and receiver_id <> sender_id and (receiver_id=:user_id or sender_id=:user_id)");
   query.setParameter("user_id", user.getId());
   query.setParameter("id", id);
   final int updated = query.executeUpdate();
   if (updated == 0) {
     final Query query2 =
         entityManager.createNativeQuery(
             "delete from MESSAGES where ID=:id and (receiver_id=:user_id or sender_id=:user_id)");
     query2.setParameter("id", id);
     query2.setParameter("user_id", user.getId());
     query2.executeUpdate();
   }
 }
Example #23
0
 /**
  * Removes a work.
  *
  * @param workId The id of the work that will be removed from the client profile
  * @param clientOrcid The client orcid
  * @return true if the work was deleted
  */
 @Override
 @Transactional
 public boolean removeWorks(String clientOrcid, List<Long> workIds) {
   Query query = entityManager.createNativeQuery("DELETE FROM work WHERE work_id in (:workIds)");
   query.setParameter("workIds", workIds);
   return query.executeUpdate() > 0;
 }
Example #24
0
 public void removeCurrentExperimentFromUsers(Experiment experiment) {
   String queryString =
       "update User u set currentExperiment=null where currentExperiment.id=:experimentId";
   Query query = dao.getEntityManager().createQuery(queryString);
   query.setParameter("experimentId", experiment.getId());
   query.executeUpdate();
 }
 public void _endpoint_clear_rest(CommandInterpreter commandInterpreter) {
   this.em.getTransaction().begin();
   Query query = this.em.createQuery("DELETE FROM RESTEndpoint");
   int deletedREST = query.executeUpdate();
   commandInterpreter.println("Deleted " + deletedREST + " RESTEndpoints.");
   this.em.getTransaction().commit();
 }
 @TransactionAttribute(REQUIRES_NEW)
 public int clearAllIndexTimes() {
   Query clearIndexTimes =
       em.createQuery("UPDATE DvObject o SET o.indexTime = NULL, o.permissionIndexTime = NULL");
   int numRowsUpdated = clearIndexTimes.executeUpdate();
   return numRowsUpdated;
 }
 private void separatePrivateMessagesFromWorkout(final Long id) {
   final Query query =
       entityManager.createNativeQuery(
           "UPDATE MESSAGES SET WORKOUT_ID=NULL WHERE WORKOUT_ID=:id AND RECEIVER_ID IS NOT NULL");
   query.setParameter("id", id);
   query.executeUpdate();
 }
Example #28
0
 public void disableTransaction(int id_transaction) {
   Query q =
       getEntityManager()
           .createNativeQuery(
               "UPDATE customer_transactions set insurance_status = false where id_transaction = ?");
   q.setParameter(1, id_transaction);
   q.executeUpdate();
 }
 public int clearIndexTimes(long dvObjectId) {
   Query clearIndexTimes =
       em.createQuery(
           "UPDATE DvObject o SET o.indexTime = NULL, o.permissionIndexTime = NULL WHERE o.id =:dvObjectId");
   clearIndexTimes.setParameter("dvObjectId", dvObjectId);
   int numRowsUpdated = clearIndexTimes.executeUpdate();
   return numRowsUpdated;
 }
 public void partGroup(final User user, final Long groupId) {
   final Query query =
       entityManager.createNativeQuery(
           "DELETE FROM GROUP_USER WHERE GROUP_ID=:groupId AND USER_ID=:userId");
   query.setParameter("groupId", groupId);
   query.setParameter("userId", user.getId());
   query.executeUpdate();
 }