@Update
 public MethodOutcome update(
     HttpServletRequest theRequest,
     @ResourceParam T theResource,
     @IdParam IdDt theId,
     @ConditionalUrlParam String theConditional) {
   startRequest(theRequest);
   try {
     if (theConditional != null) {
       return getDao().update(theResource, theConditional);
     } else {
       theResource.setId(theId);
       return getDao().update(theResource);
     }
   } catch (ResourceNotFoundException e) {
     ourLog.info(
         "Can't update resource with ID["
             + theId.getValue()
             + "] because it doesn't exist, going to create it instead");
     theResource.setId(theId);
     return getDao().create(theResource);
   } finally {
     endRequest(theRequest);
   }
 }
 private T findModel(List<S> list, ConvertTool.ModelCall<S, T> mc) {
   if (null == list) {
     throw new RuntimeException("没有属性结构");
   }
   Map<ID, T> p = new HashMap<ID, T>(list.size() + 1);
   // 最外层,默认为0
   T root = (T) new SimpleEasyUiTree();
   root.setId((ID) list.get(0).getParentId());
   root.setId(0);
   p.put((ID) root.getId(), (T) root);
   findModel(list, p, mc);
   root.setId(null);
   return root;
 }
Beispiel #3
0
  @Override
  public List<Long> addPersonRecords(Collection<T> personRecords) {
    Assert.notNull(personRecords, "Person records parameter must be specified");
    TransactionHelper transactionHelper = new TransactionHelper();

    try {
      transactionHelper.open();
      entityManager.joinTransaction();

      List<Long> idList = new ArrayList<Long>();
      Iterator<T> iterator = personRecords.iterator();
      while (iterator.hasNext()) {
        T personRecord = iterator.next();
        T merged = entityManager.merge(personRecord);
        entityManager.persist(merged);
        Long id = merged.getId();
        personRecord.setId(id);
        idList.add(id);
      }

      transactionHelper.close();
      return idList;

    } catch (Throwable e) {
      log.error(e);
      transactionHelper.fault(e);
      throw ExceptionUtil.rewrap(e);
    }
  }
  private <T extends ReviewRequestBase> T fillReviewRequestBase(
      T reviewRequest, JSONObject jsonReviewRequest) throws JSONException {

    reviewRequest.setId(jsonReviewRequest.getInt("id"));
    reviewRequest.setSummary(jsonReviewRequest.getString("summary"));
    reviewRequest.setTestingDone(jsonReviewRequest.getString("testing_done"));
    reviewRequest.setDescription(jsonReviewRequest.getString("description"));
    reviewRequest.setPublic(jsonReviewRequest.getBoolean("public"));
    reviewRequest.setBranch(jsonReviewRequest.getString("branch"));

    // bugs
    reviewRequest.setBugsClosed(readStringArray(jsonReviewRequest, "bugs_closed"));

    // target people
    JSONArray jsonTargetPeople = jsonReviewRequest.getJSONArray("target_people");
    List<String> targetPeople = new ArrayList<String>();
    for (int j = 0; j < jsonTargetPeople.length(); j++)
      targetPeople.add(jsonTargetPeople.getJSONObject(j).getString("title"));
    reviewRequest.setTargetPeople(targetPeople);

    // target groups
    JSONArray jsonTargetGroups = jsonReviewRequest.getJSONArray("target_groups");
    List<String> targetGroups = new ArrayList<String>();
    for (int j = 0; j < jsonTargetGroups.length(); j++)
      targetGroups.add(jsonTargetGroups.getJSONObject(j).getString("title"));
    reviewRequest.setTargetGroups(targetGroups);

    return reviewRequest;
  }
 /**
  * Return the persistent instance of the given entity class with the given identifier, or null if
  * there is no such persistent instance. (If the instance is already associated with the session,
  * return that instance. This method never returns an uninitialized instance.)
  *
  * @param id an identifier
  * @return a persistent instance or null
  * @throws HibernateException Indicates a problem either translating the criteria to SQL,
  *     executing the SQL or processing the SQL results.
  */
 @SuppressWarnings("unchecked")
 public T getById(K id) {
   T result = null;
   Session session = null;
   // get the current session
   session = sessionFactory.getCurrentSession();
   try {
     // perform database access (query, insert, update, etc) here
     try {
       if (id.getClass().getName().startsWith(this.getClass().getPackage().getName())) {
         result = clazz.newInstance();
         result.setId(id);
         result = (T) session.get(clazz, result);
       } else {
         result = (T) session.get(clazz, id);
       }
     } catch (InstantiationException e) {
       result = (T) session.get(clazz, id);
     } catch (IllegalAccessException e) {
       result = (T) session.get(clazz, id);
     }
   } catch (HibernateException e) {
     exceptionHandling(e, session);
   }
   // return result, if needed
   return result;
 }
 /**
  * Return the persistent instance of the given entity class with the given identifier, assuming
  * that the instance exists. This method might return a proxied instance that is initialized
  * on-demand, when a non-identifier method is accessed.
  *
  * <p>You should not use this method to determine if an instance exists (use get() instead). Use
  * this only to retrieve an instance that you assume exists, where non-existence would be an
  * actual error.
  *
  * @param id an identifier
  * @return a persistent instance or null
  * @throws HibernateException Indicates a problem either translating the criteria to SQL,
  *     executing the SQL or processing the SQL results.
  */
 @SuppressWarnings("unchecked")
 public T loadById(K id) {
   T result = null;
   Session session = null;
   // get the current session
   session = sessionFactory.getCurrentSession();
   try {
     // perform database access (query, insert, update, etc) here
     try {
       T t = clazz.newInstance();
       t.setId(id);
     } catch (InstantiationException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     result = (T) session.load(clazz, id);
   } catch (HibernateException e) {
     exceptionHandling(e, session);
   }
   // return result, if needed
   return result;
 }
Beispiel #7
0
  /*
   * (non-Javadoc)
   *
   * @see com.opendroid.db.dao.DAO#create(java.lang.Object)
   */
  public void create(T model) {

    int id = (int) db.insert(getTableName(), "0.0", values(model));

    if (id != -1) {
      model.setId(id);
    }
  }
Beispiel #8
0
 public void create(T obj) {
   String key = kayVeepUtilities.getKey();
   obj.setId(key);
   this.data.store(obj);
   this.updateMapping(obj);
   Long createdTime = System.currentTimeMillis();
   this.created.store(obj.getId(), createdTime);
   obj.set("created_time", createdTime);
 }
Beispiel #9
0
 @Override
 public T map(SQLiteStatement stmt) throws SQLiteException {
   T data = newObject();
   data.setId(stmt.columnInt(0));
   data.setName(stmt.columnString(1));
   data.setCreatedTime(stmt.columnLong(2));
   data.setUpdateTime(stmt.columnLong(3));
   data.setDeleted(stmt.columnInt(4) == 1);
   return data;
 }
Beispiel #10
0
  @Override
  public T add(T entityObject) {
    entityObject.setId(null);

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(String.format("Adding a new record [%s].", entityObject));
    }

    return this.genericRepository.save(entityObject);
  }
  @Test
  /* code */ public void whenResourceIsCreatedWithNonNullId_then409IsReceived() {
    final T resourceWithId = createNewResource();
    resourceWithId.setId(5l);

    // When
    final Response response = getApi().createAsResponse(resourceWithId);

    // Then
    assertThat(response.getStatusCode(), is(409));
  }
  @Test
  /* code */ public void givenResourceDoesNotExist_whenResourceIsUpdated_then404IsReceived() {
    // Given
    final T unpersistedEntity = createNewResource();
    unpersistedEntity.setId(IDUtil.randomPositiveLong());

    // When
    final Response response = getApi().updateAsResponse(unpersistedEntity);

    // Then
    assertThat(response.getStatusCode(), is(404));
  }
  @Override
  public T create(T obj) {
    long id = db.insert(getTableName(), null, createContentValue(obj));

    obj.unlockIdentifier();
    obj.setId(id);
    obj.lockIdentifier();

    saveRelatedData(obj);

    return obj;
  }
Beispiel #14
0
 /**
  * delete element that has specified attribute within descendant element of oneself. you can't
  * delete oneself.
  *
  * @param target
  * @return if success to delete, return true. if no hit, return false.
  */
 public <T extends AbstractJaxb> boolean remove(T target) {
   String id = target.getId();
   if (id == null) {
     for (int i = 0; i < 256; i++) {
       id = UUID.randomUUID().toString();
       if (this.getById(id) == null) {
         target.setId(id);
         break;
       }
     }
   }
   return RemoveByIdUtil.removeById(id, this);
 }
Beispiel #15
0
 /**
  * replace element that has specified attribute within descendant element of oneself. you can't
  * replace oneself. It will be replaced by deep copy of "replacement"
  *
  * @param target
  * @param replacement
  * @return if success to replace, return true. if no hit, return false.
  * @throws TagTypeUnmatchException
  */
 public <T extends AbstractJaxb> boolean replace(T target, T replacement)
     throws TagTypeUnmatchException {
   String id = target.getId();
   if (id == null) {
     for (int i = 0; i < 256; i++) {
       id = UUID.randomUUID().toString();
       if (this.getById(id) == null && replacement.getById(id) == null) {
         target.setId(id);
         break;
       }
     }
   }
   return ReplaceByIdUtil.replaceById(id, this, replacement);
 }
 public T get(String id) {
   GetResponse result = client.prepareGet(index, entity, id).execute().actionGet();
   String source = result.getSourceAsString();
   System.out.println("Loaded SLA: " + source);
   try {
     T entity = mapper.readValue(source, clazz);
     entity.setId(result.getId());
     logger.info("Successfully obtained entity with id [{}]", id);
     return entity;
   } catch (IOException e) {
     logger.error("Error retrieving entity with id " + id, e);
     return null;
   }
 }
 @Override
 public String insert(T entity) throws DataAccessException {
   if (null != entity) {
     String id = Shiro.get().getId();
     entity.setId(ObjectID.id());
     entity.setCreator(id);
     entity.setModifier(id);
     entity.setCreated(DateUtils.getTime24());
     entity.setModified(DateUtils.getTime24());
     if (mapper.iKettleLogsMapper.insert(entity) > 0) {
       return entity.getId();
     }
   }
   return null;
 }
 public static <T extends BaseEntity> T create(Class<T> baseEntityClass) {
   T obj = null;
   try {
     obj = baseEntityClass.newInstance();
   } catch (Exception e) {
     logger.log(Level.SEVERE, "Instantiating " + baseEntityClass.getName(), e);
     return (null);
   }
   obj.setId(rand.nextInt(5000));
   Calendar cal = Calendar.getInstance();
   cal.setTime(new Date());
   obj.setCreatedDate(cal);
   obj.setModifiedDate(cal);
   return (obj);
 }
 @Override
 public void saveOrUpdateAll(List<T> objects) {
   logger.debug("invoke saveOrUpdateAll on " + type.getSimpleName());
   for (T object : objects) {
     T existing = get(object.getId());
     if (existing != null) {
       logger.debug("update object :" + object.getId());
       getHibernateTemplate().evict(existing);
       object.setId(existing.getId());
     } else {
       logger.debug("save object :" + object.getId());
     }
   }
   getHibernateTemplate().saveOrUpdateAll(objects);
   getHibernateTemplate().flush();
 }
Beispiel #20
0
 @Override
 public T cursorToEntity(Cursor cursor, int index) {
   T entity = null;
   try {
     entity = getEntityClass().newInstance();
     int i = index;
     entity.setId(cursor.getLong(i));
     i++;
     entity.setName(cursor.getString(i));
   } catch (InstantiationException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   }
   return entity;
 }
 private T createInteractiveElement(
     final long instanceId, final short type, final byte[] data, final boolean isDummy) {
   final ObjectFactory<T> factory = this.m_configuration.getFactory(type);
   if (factory == null) {
     InteractiveElementFactory.m_logger.error(
         (Object)
             ("Aucune factory d'enregistr\u00e9e pour un \u00e9l\u00e9ment interactif de type "
                 + type));
     return null;
   }
   final T element = factory.makeObject();
   if (isDummy) {
     element.setIsDummy();
   }
   element.setId(instanceId);
   element.setModelId(type);
   element.fromBuild(data);
   return element;
 }
 /**
  * Saves an entity into elastic search.
  *
  * @param object The entity to save.
  */
 public void save(T object) {
   try {
     IndexRequestBuilder indexRequestBuilder =
         object.getId() == null
             ? client.prepareIndex(index, entity)
             : client.prepareIndex(index, entity, object.getId());
     IndexResponse response =
         indexRequestBuilder.setSource(mapper.writeValueAsString(object)).execute().actionGet();
     // Force refresh.
     object.setId(response.getId());
     client.admin().indices().prepareRefresh(index).execute().actionGet();
     if (logger.isDebugEnabled()) {
       BytesStreamOutput out = new BytesStreamOutput(1024 * 1024);
       response.writeTo(out);
       logger.debug("Obtained response: {}", new String(out.bytes().array()));
     }
   } catch (ElasticSearchException | IOException e) {
     logger.error("Error while saving entity", e);
   }
 }
  @Override
  public T saveOrUpdate(T obj) {

    validate(obj);

    if (obj.getId() == 0) {
      getDb().store(obj);
      long id = getDb().ext().getID(obj);

      obj.setId(id);
      getDb().store(obj);
    } else {
      T found = findById(obj.getId());

      if (found == null) throw new RuntimeException("The object does not exist in DB.");

      getDb().store(obj);
    }

    return obj;
  }
 /** @see SerializedObjectDAO#convertSerializedObject(Class, SerializedObject) */
 @SuppressWarnings("unchecked")
 public <T extends OpenmrsObject> T convertSerializedObject(
     Class<T> clazz, SerializedObject serializedObject) throws DAOException {
   if (serializedObject == null) {
     return null;
   }
   OpenmrsSerializer serializer = getSerializer(serializedObject);
   T obj = null;
   try {
     Class<?> subtype = Context.loadClass(serializedObject.getSubtype());
     obj = (T) serializer.deserialize(serializedObject.getSerializedData(), subtype);
   } catch (Exception e) {
     // Do nothing here. Handled by null check below
   }
   if (obj == null) {
     throw new DAOException("Unable to deserialize object: " + serializedObject);
   }
   obj.setId(serializedObject.getId());
   obj.setUuid(serializedObject.getUuid());
   return obj;
 }
 @SuppressWarnings("unchecked")
 public <T extends IEntity> T toEntity(T entityObject) throws Exception {
   EntityMeta _entityMeta = EntityMeta.createAndGet(entityObject.getClass());
   Object _primaryKeyObject = null;
   if (_entityMeta.isMultiplePrimaryKey()) {
     _primaryKeyObject = _entityMeta.getPrimaryKeyClass().newInstance();
     //
     entityObject.setId((Serializable) _primaryKeyObject);
   }
   for (EntityMeta.PropertyMeta _meta : _entityMeta.getProperties()) {
     Object _fValue = getObject(_meta.getName());
     if (_fValue != null) {
       if (_entityMeta.isPrimaryKey(_meta.getName()) && _entityMeta.isMultiplePrimaryKey()) {
         _meta.getField().set(_primaryKeyObject, _fValue);
       } else {
         _meta.getField().set(entityObject, _fValue);
       }
     }
   }
   return entityObject;
 }
Beispiel #26
0
  public Map<Integer, List<T>> getVipFullInfoSeqMap(List<Integer> ids, List<Integer> types) {
    TimeCost cost =
        TimeCost.begin("VipFullInfoReaderAdapter.getVipFullInfoSeqMap id size: " + ids.size());
    VipFullDataReaderPrx prx = null;
    Map<Integer, VipFullDataN[]> data;

    try {
      prx = getVipFullDataReaderPrx(0);
      data = prx.getVipFullDataNSeqMap(MathUtil.list2array(ids), MathUtil.list2array(types));
      Map<Integer, List<T>> res = new HashMap<Integer, List<T>>();
      for (Entry<Integer, VipFullDataN[]> ent : data.entrySet()) {
        List<T> dataList = new ArrayList<T>();
        for (VipFullDataN sData : ent.getValue()) {
          T o = _fullFactory.create();
          P p = _memberFactory.create();
          p.parse(sData.memberData);
          o.setMemberInfo(p);

          o.setId(sData.id);
          o.setIconUrl(sData.iconUrl);
          o.setHatUrl(sData.hatUrl);
          o.setHatStatus(sData.hatStatus);
          dataList.add(o);
        }
        res.put(ent.getKey(), dataList);
      }
      return res;
    } catch (TimeoutException e) {
      Oce.getLogger()
          .error(
              this.getClass().getName()
                  + ".getVipFullInfoSeqMap ["
                  + prx
                  + "] id="
                  + " Ice.TimeoutException");
      throw e;
    } finally {
      cost.endFinally();
    }
  }
Beispiel #27
0
 /**
  * creating a new record
  *
  * @param <T> POJOs must extend DefaultRecord
  * @param record record to save
  * @return the entity encapsulating the record in the database
  */
 private <T extends Record> RecordWrapper createRecordWrapper(T record) {
   RecordWrapper wrapper = new RecordWrapper();
   RecordType recordType = mc.getType(record.getClass(), false);
   wrapper.setRecordType(recordType.getId());
   wrapper.setData(mc.toWrapper(record));
   ////        if (record.isDocumentChanged()) {
   ////            wrapper.setDocument(record.getDocument());
   ////        }
   // -- tenant management
   Object tenant =
       mc.getTransactionEntityManager()
           .getProperties()
           .get(EntityManagerProperties.MULTITENANT_PROPERTY_DEFAULT);
   if (tenant != null) {
     wrapper.setTenant(tenant.toString());
   }
   // -- getting the id from the JPA
   mc.getTransactionEntityManager().persist(wrapper);
   Long recordId = wrapper.getId();
   record.setId(recordId);
   return wrapper;
 }
Beispiel #28
0
  /**
   * 根据对象ID集合, 整理合并集合.
   *
   * <p>页面发送变更后的子对象id列表时,在Hibernate中删除整个原来的子对象集合再根据页面id列表创建一个全新的集合这种看似最简单的做法是不行的.
   * 因此采用如此的整合算法:在源集合中删除id不在目标集合中的对象,根据目标集合中的id创建对象并添加到源集合中. 因为新建对象只有ID被赋值,
   * 因此本函数不适合于cascade-save-or-update自动持久化子对象的设置.
   *
   * @param srcObjects 源集合,元素为对象.
   * @param checkedIds 目标集合,元素为ID.
   * @param clazz 集合中对象的类型,必须为IdEntity子类
   */
  public static <T extends IdEntity> void mergeByCheckedIds(
      final Collection<T> srcObjects, final Collection<Long> checkedIds, final Class<T> clazz) {

    // 参数校验
    Assert.notNull(srcObjects, "scrObjects不能为空");
    Assert.notNull(clazz, "clazz不能为空");

    // 目标集合为空, 删除源集合中所有对象后直接返回.
    if (checkedIds == null) {
      srcObjects.clear();
      return;
    }

    // 遍历源对象集合,如果其id不在目标ID集合中的对象删除.
    // 同时,在目标集合中删除已在源集合中的id,使得目标集合中剩下的id均为源集合中没有的id.
    Iterator<T> srcIterator = srcObjects.iterator();
    try {

      while (srcIterator.hasNext()) {
        T element = srcIterator.next();
        Long id = element.getId();

        if (!checkedIds.contains(id)) {
          srcIterator.remove();
        } else {
          checkedIds.remove(id);
        }
      }

      // ID集合目前剩余的id均不在源集合中,创建对象,为id属性赋值并添加到源集合中.
      for (Long id : checkedIds) {
        T element = clazz.newInstance();
        element.setId(id);
        srcObjects.add(element);
      }
    } catch (Exception e) {
      throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
    }
  }
Beispiel #29
0
 @Override
 public <T extends AbstractUserMessagesProcessor> void saveProcessor(
     T processor, String uniqueFieldName, String uniqueFieldValue)
     throws DuplicateMySocioObjectException {
   @SuppressWarnings("unchecked")
   Query<T> q =
       (Query<T>)
           processorsDs
               .createQuery(processor.getClass())
               .field(uniqueFieldName)
               .equal(uniqueFieldValue);
   String userId = processor.getUserId();
   if (userId != null) {
     q.field("userId").equal(userId);
   }
   AbstractUserMessagesProcessor existingProcessor = q.get();
   if (existingProcessor != null) {
     processor.setId(existingProcessor.getId());
     logger.info("Duplicate processor for query: " + q.toString());
     throw new DuplicateMySocioObjectException("Duplicate processor for query: " + q.toString());
   }
   processorsDs.save(processor);
 }
Beispiel #30
0
  @Override
  public Long addPersonRecord(T personRecord) {
    Assert.notNull(personRecord, "Person record parameter must be specified");
    TransactionHelper transactionHelper = new TransactionHelper();

    try {
      transactionHelper.open();
      entityManager.joinTransaction();

      T merged = entityManager.merge(personRecord);
      entityManager.persist(merged);
      transactionHelper.close();

      Long id = merged.getId();
      personRecord.setId(id);
      return id;

    } catch (Throwable e) {
      log.error(e);
      transactionHelper.fault(e);
      throw ExceptionUtil.rewrap(e);
    }
  }