protected HttpHeaders attachmentList(T entity, String category) { HttpServletRequest request = getRequest(); String url = request.getServletPath(); AttachmentFileService attachmentFileService = SpringContextHolder.getBean(AttachmentFileService.class); List<AttachmentFile> attachmentFiles = attachmentFileService.findBy( entity.getClass().getName(), String.valueOf(entity.getId()), category); List<Map<String, Object>> filesResponse = Lists.newArrayList(); for (AttachmentFile attachmentFile : attachmentFiles) { Map<String, Object> dataMap = Maps.newHashMap(); dataMap.put("id", attachmentFile.getId()); dataMap.put("attachmentName", "_attachment_" + attachmentFile.getEntityFileCategory()); dataMap.put("name", attachmentFile.getFileRealName()); dataMap.put("size", FileUtils.byteCountToDisplaySize(attachmentFile.getFileLength())); dataMap.put( "url", getRequest().getContextPath() + StringUtils.substringBefore(url, "!attachmentList") + "!attachmentDownload?id=" + entity.getId() + "&attachmentId=" + attachmentFile.getId()); filesResponse.add(dataMap); } Map<String, List<Map<String, Object>>> response = Maps.newHashMap(); response.put("files", filesResponse); setModel(response); return buildDefaultHttpHeaders(); }
public T create(T toCreate) throws HttpException { Response<T> response = DefaultRequestHandler.getInstance() .doRequest(HttpMethod.POST, getResourcesPath(), toCreate); I id = (I) (toCreate.getId() == null ? getCreatedId(response) : toCreate.getId()); return get(id); }
private <T extends SingularityMachineAbstraction<T>> CheckResult check( T object, AbstractMachineManager<T> manager) { Optional<T> existingObject = manager.getObject(object.getId()); if (!existingObject.isPresent()) { manager.saveObject(object); return CheckResult.NEW; } MachineState currentState = existingObject.get().getCurrentState().getState(); switch (currentState) { case ACTIVE: case FROZEN: return CheckResult.ALREADY_ACTIVE; case DEAD: case MISSING_ON_STARTUP: manager.changeState(object.getId(), MachineState.ACTIVE, Optional.<String>absent()); return CheckResult.NEW; case DECOMMISSIONED: case DECOMMISSIONING: case STARTING_DECOMMISSION: return CheckResult.DECOMMISSIONING; } throw new IllegalStateException( String.format("Invalid state %s for %s", currentState, object.getId())); }
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void delEntity(T entity) throws IllegalArgumentException, GeneralServiceException { if (entity == null) { throw new IllegalArgumentException("Entity must be not null!"); } if (entity.getId() == null) { return; } beforeEntityDelete(entity); try { if (!jpaTemplate.contains(entity)) { T attachedEntity = jpaTemplate.merge(entity); jpaTemplate.remove(attachedEntity); } else { jpaTemplate.remove(entity); } } catch (Exception e) { throw new GeneralServiceException( "Failed to delete " + entity.getClass().getSimpleName() + " with id " + entity.getId(), e); } }
@Transactional(propagation = Propagation.REQUIRED, readOnly = false) public T save(T entity) throws IllegalArgumentException, GeneralServiceException { if (entity == null) { throw new IllegalArgumentException("Entity for saving cannot be null!"); } T savedEntity = null; try { if (entity.getId() == null) { beforeEntityAddUpdate(entity); jpaTemplate.persist(entity); savedEntity = entity; } else { savedEntity = jpaTemplate.merge(entity); } } catch (Exception e) { if (entity.getId() == null) { throw new GeneralServiceException("Failed to add " + entity.getClass().getSimpleName(), e); } else { throw new GeneralServiceException( "Failed to update " + entity.getClass().getSimpleName() + " with id " + entity.getId(), e); } } return savedEntity; }
public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException { if (object instanceof IUniqueObject) { IUniqueObject uniqueObject = (IUniqueObject) object; Cache cache = cm.getCache("Objects"); String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue(); Element element = cache.get(key); if (element != null) { ((SocioObject) object).setId((ObjectId) element.getValue()); return; } @SuppressWarnings("unchecked") Query<T> q = (Query<T>) ds.createQuery(object.getClass()) .field(uniqueObject.getUniqueFieldName()) .equal(uniqueObject.getUniqueFieldValue()); T objectT = (T) q.get(); if (objectT != null) { ((SocioObject) object).setId(objectT.getId()); element = new Element(key, objectT.getId()); cache.put(element); logger.info( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); throw new DuplicateMySocioObjectException( "Duplicate object of type: " + object.getClass() + " for query: " + q.toString()); } } ds.save(object); }
/** * Simply queues/schedules the object for deletion. * * @return true if the object was actually added to {@link #deletionQueue} for deletion. */ @SuppressWarnings("unchecked") protected <T extends Identifiable> boolean queueSimple(Class<? super T> type, T object) { if (object == null) return false; Long id = object.getId(); if (id == null) return false; final Timestamp ts = object.getSubmissionTs(); if (!(submissionTs == null | (submissionTs.equals(ts) || additionalTs != null && additionalTs.equals(ts)))) return false; Map<Long, T> deletedIds = (HashMap<Long, T>) deletionQueue.get(type); if (deletedIds == null) { deletedIds = new HashMap<Long, T>(); deletionQueue.put((Class<Identifiable>) type, deletedIds); } boolean result; if (deletedIds.containsKey(id)) result = false; else { deletedIds.put(object.getId(), object); result = true; } if (log.isTraceEnabled()) log.trace( "queing the deletion of <" + type.getSimpleName() + ", " + object.getId() + ">, result is: " + result); return result; }
public String getPreferredStringForItem(Object o) { if (o == null) { return null; } T t = (T) o; return t.getId() == null ? "" : t.getId(); }
@NotNull public static <T extends Named & ExternalConfigPathAware & Identifiable> ExternalProjectPojo from( @NotNull T data) { String projectUniqueName = StringUtil.isEmpty(data.getId()) ? data.getExternalName() : data.getId(); return new ExternalProjectPojo(projectUniqueName, data.getLinkedExternalProjectPath()); }
/** * 判断当前实体对象是否已持久化对象 一般用于前端页面OGNL语法计算<s:property * value="%{persistentedModel?'doUpdate':'doCreate'}"/> * * @return */ public boolean isPersistentedModel() { if (bindingEntity != null && bindingEntity.getId() != null && String.valueOf(bindingEntity.getId()).trim().length() > 0) { return true; } return false; }
/** * Groups the entities by id. Entities with null id are also included. * * @param entities * @return entities grouped by id */ public static <T extends BaseEntity> Map<Long, Set<T>> byId(Collection<? extends T> entities) { Map<Long, Set<T>> result = new HashMap<Long, Set<T>>(); for (T each : entities) { if (!result.containsKey(each.getId())) { result.put(each.getId(), new HashSet<T>()); } result.get(each.getId()).add(each); } return result; }
protected final void createInternal( final T resource, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { RestPreconditions.checkRequestElementNotNull(resource); RestPreconditions.checkRequestState(resource.getId() == null); try { getService().create(resource); } // this is so that the service layer can MANUALLY throw exceptions that get handled by the // exception translation mechanism catch (final IllegalStateException illegalState) { logger.error( "IllegalArgumentException on create operation for: " + resource.getClass().getSimpleName()); logger.warn( "IllegalArgumentException on create operation for: " + resource.getClass().getSimpleName(), illegalState); throw new ConflictException(illegalState); } catch (final DataIntegrityViolationException ex) { // on unique constraint logger.error( "DataIntegrityViolationException on create operation for: " + resource.getClass().getSimpleName()); logger.warn( "DataIntegrityViolationException on create operation for: " + resource.getClass().getSimpleName(), ex); throw new ConflictException(ex); } catch ( final InvalidDataAccessApiUsageException dataEx) { // on saving a new Resource that also contains new/unsaved entities logger.error( "InvalidDataAccessApiUsageException on create operation for: " + resource.getClass().getSimpleName()); logger.warn( "InvalidDataAccessApiUsageException on create operation for: " + resource.getClass().getSimpleName(), dataEx); throw new ConflictException(dataEx); } catch (final DataAccessException dataEx) { logger.error( "Generic DataAccessException on create operation for: " + resource.getClass().getSimpleName()); logger.warn( "Generic DataAccessException on create operation for: " + resource.getClass().getSimpleName(), dataEx); throw new ConflictException(dataEx); } // - note: mind the autoboxing and potential NPE when the resource has null id at this point // (likely when working with DTOs) eventPublisher.publishEvent( new ResourceCreatedEvent<T>(clazz, uriBuilder, response, resource.getId())); }
public void store(T obj) { if (obj.getId() == null) { create(obj); return; } this.data.store(obj); this.updateMapping(obj); Long updatedTime = System.currentTimeMillis(); this.updated.store(obj.getId(), updatedTime); obj.set("updated_time", updatedTime); }
@Override public String toDOT() { String result = "digraph G {\n"; result += "graph [fontname=\"Helvetica\" fontsize=\"10\" nodesep=\"0.35\" ranksep=\"0.25 equally\"];\n"; result += "node [fontname=\"Helvetica\" fontsize=\"10\" fixedsize=\"true\" style=\"filled\" fillcolor=\"white\" penwidth=\"2\"];\n"; result += "edge [fontname=\"Helvetica\" fontsize=\"10\" arrowhead=\"normal\" color=\"black\"];\n"; result += "\n"; result += "node [shape=circle];\n"; for (P p : this.getPlaces()) { Integer n = this.marking.get(p); String label = ((n == 0) || (n == null)) ? p.getLabel() : p.getLabel() + "[" + n.toString() + "]"; result += String.format( "\tn%s[label=\"%s\" width=\".3\" height=\".3\"];\n", p.getId().replace("-", ""), label); } result += "\n"; result += "node [shape=box];\n"; for (T t : this.getTransitions()) { String fillColor = this.isEnabled(t) ? " fillcolor=\"#9ACD32\"" : ""; if (t.isSilent()) result += String.format( "\tn%s[label=\"\" width=\".3\"" + fillColor + " height=\".1\"];\n", t.getId().replace("-", "")); else result += String.format( "\tn%s[label=\"%s\" width=\".3\"" + fillColor + " height=\".3\"];\n", t.getId().replace("-", ""), t.getLabel()); } result += "\n"; for (F f : this.getFlow()) { result += String.format( "\tn%s->n%s;\n", f.getSource().getId().replace("-", ""), f.getTarget().getId().replace("-", "")); } result += "}\n"; return result; }
@Transactional public void create(final T entity) { check(entity); Preconditions.checkNotNull(entity); Preconditions.checkState(entity.getId() == null); this.getCurrentSession().save(entity); }
@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(); }
protected <R extends XMLRenderer<T>, D extends T> ModelAndView create( String xmlCrudParameters, Class<R> renderedType, Class<D> delegatedType) { logger.trace( "Request for create " + getModelName() + " with parameters " + xmlCrudParameters + "!!!"); try { R rendered = read(xmlCrudParameters, renderedType, delegatedType); T returnObject = getCrudService().add(beforeCreate((T) rendered.getDelegated())); return getXMLViewer( getInfo( getMessages() .getMessage( GeneralProperties.class.getName() + "." + GeneralProperties.INFO_TITLE.name()), getMessages() .getMessage( GeneralProperties.class.getName() + "." + GeneralProperties.CREATE_SUCCEED.name(), getModelName()), returnObject.getId().toString())); } catch (Exception e) { return handleException( e, GeneralProperties.class.getName() + "." + GeneralProperties.CREATE_FAILED.name()); } }
@Override public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) { Cache cache = cm.getCache("Messages"); String key = message.getUniqueFieldValue() + userId; Element element = cache.get(key); if (element != null) { return (Boolean) element.getValue(); } Query<UnreaddenMessage> isUnread = ds.createQuery(UnreaddenMessage.class) .field("userId") .equal(userId) .field("message") .equal(new Key<T>(T, message.getId())); Query<ReaddenMessage> isRead = ds.createQuery(ReaddenMessage.class) .field("userId") .equal(userId) .field("messageUniqueId") .equal(message.getUniqueFieldValue().toString()); Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0; element = new Element(key, new Boolean(false)); cache.put(element); return newMessage; }
/* * (non-Javadoc) * @see org.mali.dao.common.BaseDAO#remove(java.lang.Object) */ public String remove(final T domain) throws DAOException { String id = domain.getId(); getHibernateTemplate().delete(domain); return id; }
/* * (non-Javadoc) * * @see com.opendroid.db.dao.DAO#createOrUpdate(java.lang.Object) */ public void createOrUpdate(T model) { if (exists(model.getId())) { update(model); } else { create(model); } }
public void insertOrUpdate(T entity) { if (entity.getId() == null) { getEntityManager().persist(entity); } else { getEntityManager().merge(entity); } }
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()); }
@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); } }
/** * saving and cloning records * * @param <T> POJOs must extend DefaultRecord * @param recordClass class of the records to clone * @param records records to clone * @return list of cloned and saved records */ public <T extends Record> List<T> clone(Class<T> recordClass, T... records) { RecordWrapper cloneWrapper = new RecordWrapper(); List<T> list = new ArrayList<>(); mc.transaction( () -> { // saving records save(records); // cloning for (T record : records) { RecordWrapper wrapper = mc.getTransactionEntityManager().find(RecordWrapper.class, record.getId()); cloneWrapper.setRecordType(wrapper.getRecordType()); cloneWrapper.setTenant(wrapper.getTenant()); if (wrapper.getData() != null) { cloneWrapper.setData(wrapper.getData()); } //// if (wrapper.getDocument() != null) { //// cloneWrapper.setDocument(wrapper.getDocument()); //// } // performing database operations mc.getTransactionEntityManager().persist(cloneWrapper); T recordClone = mc.getRecord(recordClass, wrapper); indexRecord(true, recordClone); auditor.logCreateRecord(cloneWrapper); list.add(recordClone); } }); return list; }
/** * Update register * * @param entity */ public void update(T entity) { final String selection = BaseColumns._ID + " = ?"; final String[] selectionArgs = {String.valueOf(entity.getId())}; this.dbHelper .getWritableDatabase() .update(this.tableName, this.getContentValues(entity), selection, selectionArgs); }
public <T extends RootEntity> void write(T entity, Callback cb) { if (entity == null) return; ModelType type = ModelType.forModelClass(entity.getClass()); if (type == null || entity.getRefId() == null) { warn(cb, "no refId, or type is unknown", entity); return; } if (conf.hasVisited(type, entity.getId())) return; Writer<T> writer = getWriter(entity, conf); if (writer == null) { warn(cb, "no writer found for type " + type, entity); return; } try { conf.refFn = ref -> { write(ref, cb); }; JsonObject obj = writer.write(entity); conf.store.put(type, obj); if (writer.isExportExternalFiles()) writeExternalFiles(entity, type, cb); if (cb != null) cb.apply(Message.info("data set exported"), entity); } catch (Exception e) { e.printStackTrace(); if (cb != null) cb.apply(Message.error("failed to export data set", e), entity); } }
protected void attachmentDownload(T entity, String attachmentId) { try { AttachmentFileService attachmentFileService = SpringContextHolder.getBean(AttachmentFileService.class); AttachmentFile attachmentFile = attachmentFileService.findOne(attachmentId); if (attachmentFile != null && entity.getId().toString().equals(attachmentFile.getEntityId()) && entity.getClass().getName().equals(attachmentFile.getEntityClassName())) { HttpServletResponse response = ServletActionContext.getResponse(); ServletUtils.setFileDownloadHeader(response, attachmentFile.getFileRealName()); response.setContentType(attachmentFile.getFileType()); DynamicConfigService dynamicConfigService = SpringContextHolder.getBean(DynamicConfigService.class); String rootPath = dynamicConfigService.getFileUploadRootDir(); File diskFile = new File( rootPath + attachmentFile.getFileRelativePath() + File.separator + attachmentFile.getDiskFileName()); logger.debug("Downloading attachment file from disk: {}", diskFile.getAbsolutePath()); ServletUtils.renderFileDownload(response, FileUtils.readFileToByteArray(diskFile)); } } catch (Exception e) { logger.error("Download file error", e); } }
@Test public void testCreateAndReadOne() { String name = "crud controller read one"; assertFalse(findByName(name).isPresent()); T entity = createEntity(name); getService().create(entity); assertNotNull(entity.getId()); assertTrue(findByName(name).isPresent()); JsonNode result = performAuthenticatedRequestAndReturnJsonNode( getAuthentication(), get(getEndPoint() + "/" + entity.getId())); assertEquals(entity.getId().toString(), result.findPath("id").asText()); assertEquals(name, result.findPath("name").asText()); }
@NotNull public TIntObjectHashMap<T> preLoadCommitData(@NotNull TIntHashSet commits) throws VcsException { TIntObjectHashMap<T> result = new TIntObjectHashMap<>(); final MultiMap<VirtualFile, String> rootsAndHashes = MultiMap.create(); commits.forEach( commit -> { CommitId commitId = myHashMap.getCommitId(commit); if (commitId != null) { rootsAndHashes.putValue(commitId.getRoot(), commitId.getHash().asString()); } return true; }); for (Map.Entry<VirtualFile, Collection<String>> entry : rootsAndHashes.entrySet()) { VcsLogProvider logProvider = myLogProviders.get(entry.getKey()); if (logProvider != null) { List<? extends T> details = readDetails(logProvider, entry.getKey(), ContainerUtil.newArrayList(entry.getValue())); for (T data : details) { int index = myHashMap.getCommitIndex(data.getId(), data.getRoot()); result.put(index, data); } saveInCache(result); } else { LOG.error( "No log provider for root " + entry.getKey().getPath() + ". All known log providers " + myLogProviders); } } return result; }
@Transactional public void update(final T entity) { check(entity); Preconditions.checkNotNull(entity.getId()); this.getCurrentSession().saveOrUpdate(entity); }