Java Code Examples for org.springframework.beans.BeanUtils

The following are top voted examples for showing how to use org.springframework.beans.BeanUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: BookingController.java   Source Code and License 7 votes vote down vote up
/**
 * Add booking with the specified information.
 *
 * @param bookingVO
 * @return A non-null booking.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Booking> add(@RequestBody BookingVO bookingVO) {
    logger.info(String.format("booking-service add() invoked: %s for %s", bookingService.getClass().getName(), bookingVO.getName()));
    System.out.println(bookingVO);
    Booking booking = new Booking(null, null, null, null, null, null, null);
    BeanUtils.copyProperties(bookingVO, booking);
    try {
        bookingService.add(booking);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
Example 2
Project: TITAN   File: LinkServiceImpl.java   Source Code and License 7 votes vote down vote up
/**
 * @desc 分页查询所有链路列表
 *
 * @author liuliang
 *
 * @param pageIndex 当前页
 * @param pageSize 每页条数
 * @return List<LinkBO> 链路BO集合
 * @throws Exception
 */
@Override
public List<LinkBO> getLinkList(String linkName,int pageIndex, int pageSize) throws Exception{
	//1、查询
	List<Link> linkList = null;
	if(StringUtils.isBlank(linkName)){
		linkList = linkDao.queryLinkByPage(pageIndex, pageSize);
	}else{
		linkList = linkDao.queryLinkByPage(linkName,pageIndex, pageSize);
	}
	//2、转换
	List<LinkBO> linkBOList = new ArrayList<LinkBO>();
	if((null != linkList) && (0 < linkList.size())){
		LinkBO linkBO = null;
		for(Link link:linkList){
			linkBO = new LinkBO();
			BeanUtils.copyProperties(link, linkBO);
			linkBOList.add(linkBO);
		}
	}
	//3、返回
	return linkBOList;
}
 
Example 3
Project: X-mall   File: UserServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ServerResponse<List<UserVo>> getUsers() {
    List<User> userList = userMapper.selectAll();
    List<UserVo> userVoList = new ArrayList<>();
    for (User user : userList) {
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userVoList.add(userVo);
    }
    return ServerResponse.createBySuccess("获取用户成功", userVoList);
}
 
Example 4
Project: lams   File: HandlerMethodInvoker.java   Source Code and License 6 votes vote down vote up
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam,
		ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception {

	// Bind request parameter onto object...
	String name = attrName;
	if ("".equals(name)) {
		name = Conventions.getVariableNameForParameter(methodParam);
	}
	Class<?> paramType = methodParam.getParameterType();
	Object bindObject;
	if (implicitModel.containsKey(name)) {
		bindObject = implicitModel.get(name);
	}
	else if (this.methodResolver.isSessionAttribute(name, paramType)) {
		bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name);
		if (bindObject == null) {
			raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session");
		}
	}
	else {
		bindObject = BeanUtils.instantiateClass(paramType);
	}
	WebDataBinder binder = createBinder(webRequest, bindObject, name);
	initBinder(handler, name, binder, webRequest);
	return binder;
}
 
Example 5
Project: configx   File: ConfigBeanFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 创建配置Bean
 *
 * @param propertyName               属性名
 * @param beanType                   配置Bean类型
 * @param converterType              转换器类型
 * @param configBeanPropertyResolver 属性解析器
 * @param conversionService          转换服务
 * @param <T>
 * @return
 */
public static <T> T createConfigBean(String propertyName, Class<T> beanType,
                                     Class<? extends ConfigBeanConverter> converterType,
                                     ConfigPropertyResolver configBeanPropertyResolver,
                                     ConfigBeanConversionService conversionService) {

    PropertyResolver propertyResolver = configBeanPropertyResolver.getObject();
    String propertyValue = propertyResolver.getRequiredProperty(propertyName);

    if (converterType != null && !converterType.isInterface()) {
        ConfigBeanConverter converter = BeanUtils.instantiate(converterType);
        return (T) converter.convert(propertyName, propertyValue, TypeDescriptor.valueOf(beanType));

    } else {
        return (T) conversionService.convert(propertyName, propertyValue, TypeDescriptor.valueOf(beanType));
    }
}
 
Example 6
Project: document-management-store-app   File: DocumentContentVersionHalResource.java   Source Code and License 6 votes vote down vote up
public DocumentContentVersionHalResource(DocumentContentVersion documentContentVersion) {
    BeanUtils.copyProperties(documentContentVersion, this);

    add(linkTo(methodOn(StoredDocumentController.class)
            .getMetaData(documentContentVersion.getStoredDocument().getId())).withRel("document"));

    add(linkTo(methodOn(DocumentContentVersionController.class).getDocumentContentVersionDocument(
            documentContentVersion.getStoredDocument().getId(),
            documentContentVersion.getId())).withRel("self"));

    add(linkTo(methodOn(DocumentContentVersionController.class).getDocumentContentVersionDocumentBinary(
            documentContentVersion.getStoredDocument().getId(),
            documentContentVersion.getId())).withRel("binary"));

    add(linkTo(methodOn(DocumentContentVersionController.class).getDocumentContentVersionDocumentPreviewThumbnail(
            documentContentVersion.getStoredDocument().getId(),
        documentContentVersion.getId())).withRel("thumbnail"));
}
 
Example 7
Project: sucok-framework   File: QueryResult.java   Source Code and License 6 votes vote down vote up
public QueryResult<T> treeSorted(String keyField, String parentKeyField, Object rootValue) {
	try {
		List<T> list = getData();
		if (list.size() <= 0) {
			return this;
		}
		Class<?> itemClass = list.get(0).getClass();
		PropertyDescriptor keyProp = BeanUtils.getPropertyDescriptor(itemClass, keyField);
		PropertyDescriptor parentKeyProp = BeanUtils.getPropertyDescriptor(itemClass, parentKeyField);
		List<T> newList = new ArrayList<>(list.size());
		addTreeNode(newList, list, rootValue, keyProp, parentKeyProp);
		setData(newList);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return this;
}
 
Example 8
Project: Yidu   File: ArticleListAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void loadData() {
    ArticleSearchBean searchBean = new ArticleSearchBean();
    BeanUtils.copyProperties(this, searchBean, new String[] { "articleno" });
    searchBean.setPageType(ArticleSearchBean.PageType.adminPage);
    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn("lastupdate");
        pagination.setSortOrder("DESC");
    }
    // 总件数设置
    pagination.setPreperties(articleService.getCount(searchBean));
    searchBean.setPagination(pagination);
    articleList = articleService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(articleList.size());
}
 
Example 9
Project: Yidu   File: ChapterEditAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化种别下拉列表选项
    initCollections(new String[] { "collectionProperties.chapter.isvip" });
    if (chapterno == 0 && articleno == 0) {
        addActionError(getText("errors.unknown"));
        return;
    }

    // 编辑
    if (chapterno != 0) {
        TChapter chapter = chapterService.getByNo(chapterno);
        BeanUtils.copyProperties(chapter, this);
        content = Utils.getContext(chapter, false);
    } else {
        // 追加的话取小说信息
        TArticle article = articleService.getByNo(articleno);
        BeanUtils.copyProperties(article, this);
    }
    logger.debug("loadData normally end.");
}
 
Example 10
Project: sporticus   File: IUserProfile.java   Source Code and License 6 votes vote down vote up
static IUserProfile COPY(final IUserProfile from, final IUserProfile to) {
    if(from == null) {
        return null;
    }
    if(to == null) {
        return null;
    }
    BeanUtils.copyProperties(from, to);
    if(from.isEnabled() != null) {
        to.setEnabled(from.isEnabled());
    }
    if(from.isVerified() != null) {
        to.setVerified(from.isVerified());
    }

    return to;
}
 
Example 11
Project: sporticus   File: IGroupMember.java   Source Code and License 6 votes vote down vote up
static IGroupMember COPY(final IGroupMember from, final IGroupMember to) {
    if (from == null) {
        return null;
    }
    if (to == null) {
        return null;
    }
    BeanUtils.copyProperties(from, to);
    if (from.isEnabled() != null) {
        to.setEnabled(from.isEnabled());
    }
    if (from.getStatus() != null) {
        to.setStatus(from.getStatus());
    }
    return to;
}
 
Example 12
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: UserController.java   Source Code and License 6 votes vote down vote up
/**
 * Add user with the specified information.
 *
 * @param userVO
 * @return A non-null user.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> add(@RequestBody UserVO userVO) {
    logger.info(String.format("user-service add() invoked: %s for %s", userService.getClass().getName(), userVO.getName()));
    System.out.println(userVO);
    User user = new User(null, null, null, null, null);
    BeanUtils.copyProperties(userVO, user);
    try {
        userService.add(user);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add User REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
Example 13
Project: FastBootWeixin   File: WxApiExecutor.java   Source Code and License 6 votes vote down vote up
private Object getObjectBody(WxApiMethodInfo wxApiMethodInfo, Object[] args) {
    MethodParameter methodParameter = wxApiMethodInfo.getMethodParameters().stream()
            .filter(p -> !BeanUtils.isSimpleValueType(p.getParameterType()) || p.hasParameterAnnotation(WxApiBody.class))
            .findFirst().orElse(null);
    if (methodParameter == null) {
        throw new WxAppException("没有可处理的参数");
    }
    // 不是简单类型
    if (!BeanUtils.isSimpleValueType(methodParameter.getParameterType())) {
        // 暂时只支持json
        return args[methodParameter.getParameterIndex()];
    }
    if (args[methodParameter.getParameterIndex()] != null) {
        return args[methodParameter.getParameterIndex()].toString();
    } else {
        return "";
    }
}
 
Example 14
Project: gemini.blueprint   File: AbstractOsgiBundleApplicationContext.java   Source Code and License 6 votes vote down vote up
/**
 * Takes care of enforcing the relationship between exporter and importers.
 * 
 * @param beanFactory
 */
private void enforceExporterImporterDependency(ConfigurableListableBeanFactory beanFactory) {
	Object instance = null;

	instance = AccessController.doPrivileged(new PrivilegedAction<Object>() {

		public Object run() {
			// create the service manager
			ClassLoader loader = AbstractOsgiBundleApplicationContext.class.getClassLoader();
			try {
				Class<?> managerClass = loader.loadClass(EXPORTER_IMPORTER_DEPENDENCY_MANAGER);
				return BeanUtils.instantiateClass(managerClass);
			} catch (ClassNotFoundException cnfe) {
				throw new ApplicationContextException("Cannot load class " + EXPORTER_IMPORTER_DEPENDENCY_MANAGER,
						cnfe);
			}
		}
	});

	// sanity check
	Assert.isInstanceOf(BeanFactoryAware.class, instance);
	Assert.isInstanceOf(BeanPostProcessor.class, instance);
	((BeanFactoryAware) instance).setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor((BeanPostProcessor) instance);
}
 
Example 15
Project: YiDu-Novel   File: ChapterEditAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化种别下拉列表选项
    initCollections(new String[] { "collectionProperties.chapter.isvip" });
    if (chapterno == 0 && articleno == 0) {
        addActionError(getText("errors.unknown"));
        return;
    }

    // 编辑
    if (chapterno != 0) {
        TChapter chapter = chapterService.getByNo(chapterno);
        BeanUtils.copyProperties(chapter, this);
        content = Utils.getContext(chapter, false);
    } else {
        // 追加的话取小说信息
        TArticle article = articleService.getByNo(articleno);
        BeanUtils.copyProperties(article, this);
    }
    logger.debug("loadData normally end.");
}
 
Example 16
Project: YiDu-Novel   File: BlockEditAction.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * <p>
 * 保存画面的内容
 * </p>
 * 
 * @return
 */
public String save() {
    logger.debug("save start.");
    // 初始化下拉列表选项
    initCollections(new String[] { "collectionProperties.article.category", "collectionProperties.block.type",
            "collectionProperties.block.target", "collectionProperties.block.sortCol",
            "collectionProperties.boolean" });
    TSystemBlock systemBlock = new TSystemBlock();
    if (blockno != 0) {
        systemBlock = systemBlockService.getByNo(blockno);
    } else {
        systemBlock.setDeleteflag(false);
    }
    BeanUtils.copyProperties(this, systemBlock);
    systemBlock.setModifytime(new Date());
    systemBlock.setModifyuserno(LoginManager.getLoginUser().getUserno());
    systemBlockService.save(systemBlock);
    logger.debug("save normally end.");
    return REDIRECT;
}
 
Example 17
Project: lams   File: AbstractJaxWsServiceExporter.java   Source Code and License 6 votes vote down vote up
private WebServiceFeature convertWebServiceFeature(Object feature) {
	Assert.notNull(feature, "WebServiceFeature specification object must not be null");
	if (feature instanceof WebServiceFeature) {
		return (WebServiceFeature) feature;
	}
	else if (feature instanceof Class) {
		return (WebServiceFeature) BeanUtils.instantiate((Class<?>) feature);
	}
	else if (feature instanceof String) {
		try {
			Class<?> featureClass = getBeanClassLoader().loadClass((String) feature);
			return (WebServiceFeature) BeanUtils.instantiate(featureClass);
		}
		catch (ClassNotFoundException ex) {
			throw new IllegalArgumentException("Could not load WebServiceFeature class [" + feature + "]");
		}
	}
	else {
		throw new IllegalArgumentException("Unknown WebServiceFeature specification type: " + feature.getClass());
	}
}
 
Example 18
Project: YiDu-Novel   File: ChapterOrderAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化种别下拉列表选项
    initCollections(new String[] { "collectionProperties.chapter.isvip" });
    if (chapterno == 0 && articleno == 0) {
        addActionError(getText("errors.unknown"));
        return;
    }

    // 编辑
    if (chapterno != 0) {
        TChapter chapter = chapterService.getByNo(chapterno);
        BeanUtils.copyProperties(chapter, this);
        content = Utils.getContext(chapter, false);
    }
    logger.debug("loadData normally end.");
}
 
Example 19
Project: Yidu   File: ArticleEditAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化类别下拉列表选项
    initCollections(new String[] { "collectionProperties.article.category",
            "collectionProperties.article.fullflag", "collectionProperties.article.firstflag",
            "collectionProperties.article.permission" });

    // 编辑
    if (articleno != 0) {
        TArticle article = articleService.getByNo(articleno);
        if (article == null) {
            addActionError(getText("errors.not.exsits.article"));
            return;
        }
        if (!checkRight(article)) {
            addActionError(getText("errors.right"));
            return;
        }

        BeanUtils.copyProperties(article, this);

    }
    logger.debug("loadData normally end.");
}
 
Example 20
Project: Yidu   File: UserEditAction.java   Source Code and License 6 votes vote down vote up
/**
 * <p>
 * 保存画面的内容
 * </p>
 * 
 * @return
 * @throws Exception
 */
public String save() {
    logger.debug("save start.");
    TUser user = new TUser();
    if (userno != 0) {
        user = userService.getByNo(userno);
    } else {
        user.setRegdate(new Date());
        user.setDeleteflag(false);
    }
    BeanUtils.copyProperties(this, user, new String[] { "regdate", "lastlogin", "password" });

    if (StringUtils.isNotEmpty(password)) {
        user.setPassword(Utils.convert2MD5(password));
    }
    user.setActivedflag(true);
    user.setModifytime(new Date());
    user.setModifyuserno(LoginManager.getLoginUser().getUserno());
    userService.save(user);
    logger.debug("save normally end.");
    return REDIRECT;
}
 
Example 21
Project: gemini.blueprint   File: ExtenderConfiguration.java   Source Code and License 6 votes vote down vote up
protected void addDefaultDependencyFactories() {
	boolean debug = log.isDebugEnabled();

	// default JDK 1.4 processor
	dependencyFactories.add(0, new MandatoryImporterDependencyFactory());

	// load through reflection the dependency and injection processors if running on JDK 1.5 and annotation
	// processing is enabled
	if (processAnnotation) {
		// dependency processor
		Class<?> annotationProcessor = null;
		try {
			annotationProcessor =
					Class.forName(ANNOTATION_DEPENDENCY_FACTORY, false, ExtenderConfiguration.class
							.getClassLoader());
		} catch (ClassNotFoundException cnfe) {
			log.warn("Gemini Blueprint extensions bundle not present, annotation processing disabled.");
			log.debug("Gemini Blueprint extensions bundle not present, annotation processing disabled.", cnfe);
			return;
		}
		Object processor = BeanUtils.instantiateClass(annotationProcessor);
		Assert.isInstanceOf(OsgiServiceDependencyFactory.class, processor);
		dependencyFactories.add(1, (OsgiServiceDependencyFactory) processor);

		if (debug)
			log.debug("Succesfully loaded annotation dependency processor [" + ANNOTATION_DEPENDENCY_FACTORY + "]");

		// add injection processor (first in line)
		postProcessors.add(0, new OsgiAnnotationPostProcessor());
		log.info("Gemini Blueprint extensions annotation processing enabled");
	} else {
		if (debug) {
			log.debug("Gemini Blueprint extensions annotation processing disabled; [" + ANNOTATION_DEPENDENCY_FACTORY
					+ "] not loaded");
		}
	}

}
 
Example 22
Project: xq_seckill_microservice   File: CrawlerServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public void saveInitializeData(byte[] dataArray) throws Exception {
    try {
        EstateItemDTO dto = ProtoStuffUtil.deserialize(dataArray, EstateItemDTO.class);
        EstateItemModel model = new EstateItemModel();

        // 先查看数据库是否已存在该记录
        dataArray = estateFeignClient.findItemByHouseCode(dto.getHouseCode());
        if (dataArray != null) {
            model = ProtoStuffUtil.deserialize(dataArray, EstateItemModel.class);
            BeanUtils.copyProperties(dto, model, "id");
            // 先删除原有图片
            estateFeignClient.deleteImagesByHouseCode(dto.getHouseCode());
        } else {
            BeanUtils.copyProperties(dto, model);
        }
        // 保存房源条目
        estateFeignClient.saveItem(ProtoStuffUtil.serialize(model));
        // 保存房源图片
        saveImages(dto);

        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setCacheable(true);
        resolver.setCharacterEncoding(AppConstants.CHARSET_UTF8);
        resolver.setTemplateMode(StandardTemplateModeHandlers.LEGACYHTML5.getTemplateModeName());
        resolver.setPrefix("templates/");//模板所在目录
        resolver.setSuffix(".html");//模板文件后缀
        //构造上下文(Model)

        Context context = new Context(Locale.CHINA, BeanMapUtil.beanToMap(dto));
        GenParam genParam = new GenParam(resolver, context, "estate_detailUI", appProperties.getProducesPath(), dto.getHouseCode());
        // 生成静态页面
        PageGenerator.staticPage(genParam);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

}
 
Example 23
Project: eventapis   File: CreateOrderCommand.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/order/v1/create", method = RequestMethod.POST)
public EventKey execute(@RequestBody @Valid CreateOrderCommandDto dto) throws Exception {

    OrderCreatedEvent orderCreatedEvent = new OrderCreatedEvent();
    BeanUtils.copyProperties(dto,orderCreatedEvent);

    EventKey eventKey = eventRepository.recordAndPublish(orderCreatedEvent);
    return eventKey;
}
 
Example 24
Project: exam   File: ExamSectionQuestion.java   Source Code and License 5 votes vote down vote up
ExamSectionQuestion copyWithAnswers() {
    ExamSectionQuestion esqCopy = new ExamSectionQuestion();
    BeanUtils.copyProperties(this, esqCopy, "id", "options", "essayAnswer", "clozeTestAnswer");
    // This is a little bit tricky. Need to map the original question options with copied ones so they can be
    // associated with both question and exam section question options :)
    Map<Long, MultipleChoiceOption> optionMap = new HashMap<>();
    Question blueprint = question.copy(optionMap);
    blueprint.setParent(question);
    blueprint.save();
    optionMap.forEach((k, optionCopy) -> {
        optionCopy.setQuestion(blueprint);
        optionCopy.save();
        Optional<ExamSectionQuestionOption> esqoo = options.stream()
                .filter(o -> o.getOption().getId().equals(k))
                .findFirst();
        if (esqoo.isPresent()) {
            ExamSectionQuestionOption esqo = esqoo.get();
            ExamSectionQuestionOption esqoCopy = esqo.copyWithAnswer();
            esqoCopy.setOption(optionCopy);
            esqCopy.getOptions().add(esqoCopy);
        } else {
            Logger.error("Failed to copy a multi-choice question option!");
            throw new RuntimeException();
        }
    });
    esqCopy.setQuestion(blueprint);
    // Essay Answer
    if (essayAnswer != null) {
        esqCopy.setEssayAnswer(essayAnswer.copy());
    }
    if (clozeTestAnswer != null) {
        esqCopy.setClozeTestAnswer(clozeTestAnswer.copy());
    }
    return esqCopy;
}
 
Example 25
Project: springboot-shiro-cas-mybatis   File: RegisteredServiceThemeBasedViewResolver.java   Source Code and License 5 votes vote down vote up
/**
 * Uses the viewName and the theme associated with the service.
 * being requested and returns the appropriate view.
 * @param viewName the name of the view to be resolved
 * @return a theme-based UrlBasedView
 * @throws Exception an exception
 */
@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service = WebUtils.getService(requestContext);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final String themeId = service != null && registeredService != null
            && registeredService.getAccessStrategy().isServiceAccessAllowed()
            && StringUtils.hasText(registeredService.getTheme()) ? registeredService.getTheme() : defaultThemeId;

    final String themePrefix = String.format("%s/%s/ui/", pathPrefix, themeId);
    LOGGER.debug("Prefix {} set for service {} with theme {}", themePrefix, service, themeId);

    //Build up the view like the base classes do, but we need to forcefully set the prefix for each request.
    //From UrlBasedViewResolver.buildView
    final InternalResourceView view = (InternalResourceView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(themePrefix + viewName + getSuffix());
    final String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }
    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    //From InternalResourceViewResolver.buildView
    view.setAlwaysInclude(false);
    view.setExposeContextBeansAsAttributes(false);
    view.setPreventDispatchLoop(true);

    LOGGER.debug("View resolved: {}", view.getUrl());

    return view;
}
 
Example 26
Project: exam   File: AutoEvaluationConfig.java   Source Code and License 5 votes vote down vote up
@Transient
public AutoEvaluationConfig copy() {
    AutoEvaluationConfig clone = new AutoEvaluationConfig();
    BeanUtils.copyProperties(this, clone, "id", "exam", "gradeEvaluations");
    for (GradeEvaluation ge : gradeEvaluations) {
        clone.getGradeEvaluations().add(ge.copy());
    }
    return clone;
}
 
Example 27
Project: configx   File: EnableConfigServiceImportSelector.java   Source Code and License 5 votes vote down vote up
private List<ConfigBeanConverter> instantiateConverters(List<Class<?>> types) {
    List<ConfigBeanConverter> converters = new ArrayList<>();
    for (Class<?> type : types) {
        ConfigBeanConverter converter = (ConfigBeanConverter) BeanUtils.instantiate(type);
        converters.add(converter);
    }
    return converters;
}
 
Example 28
Project: document-management-store-app   File: FolderHalResource.java   Source Code and License 5 votes vote down vote up
public FolderHalResource(Folder folder) {
    BeanUtils.copyProperties(folder, this);
    if (folder.getStoredDocuments() != null) {
        Resources<StoredDocumentHalResource> itemResources =
                new Resources<>(folder.getStoredDocuments()
                        .stream()
                        .map(StoredDocumentHalResource::new)
                    .collect(Collectors.toList()));
        embedResource("items", itemResources);
    }
    add(linkTo(methodOn(FolderController.class).get(folder.getId())).withSelfRel());
}
 
Example 29
Project: document-management-store-app   File: StoredDocumentAuditEntryHalResource.java   Source Code and License 5 votes vote down vote up
public StoredDocumentAuditEntryHalResource(StoredDocumentAuditEntry storedDocumentAuditEntry) {
    BeanUtils.copyProperties(storedDocumentAuditEntry, this);
    setType(storedDocumentAuditEntry.getClass().getSimpleName());
    add(linkTo(methodOn(StoredDocumentController.class).getMetaData(storedDocumentAuditEntry.getStoredDocument().getId())).withRel("document"));
    if (storedDocumentAuditEntry instanceof DocumentContentVersionAuditEntry) {
        DocumentContentVersionAuditEntry documentContentVersionAuditEntry = (DocumentContentVersionAuditEntry) storedDocumentAuditEntry;
        add(linkTo(methodOn(DocumentContentVersionController.class)
                .getDocumentContentVersionDocument(
                        storedDocumentAuditEntry.getStoredDocument().getId(),
                        documentContentVersionAuditEntry.getDocumentContentVersion().getId())).withRel("documentContentVersion"));
    }
}
 
Example 30
Project: TITAN   File: AutomaticTaskController.java   Source Code and License 5 votes vote down vote up
/**
 * @desc  删除
 *
 * @author liuliang
 *
 * @param automaticTaskBO
 * @param br
 * @return
 */
@RequestMapping(value = "/del")
@ResponseBody
public Result del(@Validated(Groups.Query.class) AutomaticTaskBO automaticTaskBO,BindingResult br) {
	Result result = new Result();
	//参数校验
	Result validateResult = ValidatorUtil.getValidResult(br);
	if(ResultUtil.isfail(validateResult)) {
		return ResultUtil.copy(validateResult, result);
	}
	//删除
	try {
		AutomaticTask automaticTask = automaticTaskService.getDataDetail(automaticTaskBO.getAutomaticTaskId());
		int delResult = automaticTaskService.del(automaticTaskBO.getAutomaticTaskId());
		if(0 < delResult) {
			// 同步定时任务
			AutomaticTaskBO obj = new AutomaticTaskBO();
			BeanUtils.copyProperties(automaticTask, obj);
			this.syncAutomaticTask(obj, TaskSyncTypeEnum.DELETE.value);
			
			return ResultUtil.success(result);
		}
	} catch (Exception e) {
		logger.error("删除数据异常,params:{}",automaticTaskBO.toString(),e);
	}
	//失败返回
	return ResultUtil.fail(ErrorCode.UPDATE_DB_ERROR,result);
}
 
Example 31
Project: rocket-console   File: MessageView.java   Source Code and License 5 votes vote down vote up
/**from Message**/

    public static MessageView fromMessageExt(MessageExt messageExt) {
        MessageView messageView = new MessageView();
        BeanUtils.copyProperties(messageExt, messageView);
        if (messageExt.getBody() != null) {
            messageView.setMessageBody(new String(messageExt.getBody(), Charsets.UTF_8));
        }
        return messageView;
    }
 
Example 32
Project: TITAN   File: AutomaticTaskServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 分页查询所有数据列表
 *
 * @author liuliang
 *
 * @param pageIndex 当前页
 * @param pageSize 每页条数
 * @return List<AutomaticTask> 数据集合
 * @throws Exception
 */
@Override
public List<AutomaticTaskBO> getDataList(int pageIndex, int pageSize)throws Exception {
	List<AutomaticTask> list = automaticTaskDao.queryAutomaticTaskByPage(pageIndex, pageSize);
	List<AutomaticTaskBO> automaticTaskBOList = new ArrayList<AutomaticTaskBO>();
	if((null != list) && (0 < list.size())){
		AutomaticTaskBO automaticTaskBO = null;
		for(AutomaticTask automaticTask:list){
			automaticTaskBO = new AutomaticTaskBO();
			BeanUtils.copyProperties(automaticTask, automaticTaskBO);
			automaticTaskBOList.add(automaticTaskBO);
		}
	}
	return automaticTaskBOList;
}
 
Example 33
Project: TITAN   File: MonitorSetServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @desc 分页查询数据列表
 *
 * @author liuliang
 *
 * @param pageIndex
 * @param pageSize
 * @return
 */
@Override
public List<MonitorSetBO> getDataList(int pageIndex, int pageSize) throws Exception {
	List<MonitorSet> list = monitorSetDao.getDataList(pageIndex, pageSize);
	List<MonitorSetBO> boList = new ArrayList<MonitorSetBO>();
	if((null != list) && (0 < list.size())){
		MonitorSetBO monitorSetBO = null;
		for(MonitorSet monitorSet:list){
			monitorSetBO = new MonitorSetBO();
			BeanUtils.copyProperties(monitorSet, monitorSetBO);
			boList.add(monitorSetBO);
		}
	}
	return boList;
}
 
Example 34
Project: Yidu   File: UserEditAction.java   Source Code and License 5 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化类别下拉列表选项
    initCollections(new String[] { "collectionProperties.user.sex", "collectionProperties.user.type" });
    // 编辑
    if (userno != 0) {
        TUser user = userService.getByNo(userno);
        BeanUtils.copyProperties(user, this);
    }
    logger.debug("loadData normally end.");
}
 
Example 35
Project: admin-shiro   File: JobDetailEditNotesService.java   Source Code and License 5 votes vote down vote up
@Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
public void addEditNote(JobDetailEditAO ao){
    JobDetailEditNotesDO jobDetailEditNotesDO = new JobDetailEditNotesDO();
    BeanUtils.copyProperties(ao, jobDetailEditNotesDO);
    jobDetailEditNotesDO.setCron(ao.getJobDetailDO().getCron());
    jobDetailEditNotesDO.setState(ao.getJobDetailDO().getState());
    jobDetailEditNotesDO.setOperatorId(SessionHolderUtils.getCurrentUid());
    jobDetailEditNotesDO.setOperatorName(SessionHolderUtils.getCurrentUname());
    daoSupport.save(jobDetailEditNotesDO);
}
 
Example 36
Project: lams   File: AbstractPropertyBindingResult.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieve the custom PropertyEditor for the given field, if any.
 * @param fixedField the fully qualified field name
 * @return the custom PropertyEditor, or {@code null}
 */
protected PropertyEditor getCustomEditor(String fixedField) {
	Class<?> targetType = getPropertyAccessor().getPropertyType(fixedField);
	PropertyEditor editor = getPropertyAccessor().findCustomEditor(targetType, fixedField);
	if (editor == null) {
		editor = BeanUtils.findEditorByConvention(targetType);
	}
	return editor;
}
 
Example 37
Project: k-framework   File: ThirdPartyRequestPayInfo.java   Source Code and License 5 votes vote down vote up
public ThirdPartyRequestPayInfo(PaymentOrderInfo orderInfo, PrepayRequestInfo requestInfo) {
    BeanUtils.copyProperties(orderInfo, this);
    this.tradeId = orderInfo.getTradeId().toString();
    this.amount = orderInfo.getAmount().multiply(BigDecimal.valueOf(100.0)).intValue();
    this.channel = requestInfo.getPayMethod().getChannel();

    this.userIp = requestInfo.getUserIp();
    this.authCode = requestInfo.getCode();
    this.openId = requestInfo.getOpenId();
}
 
Example 38
Project: lams   File: ModelFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Whether the given attribute requires a {@link BindingResult} in the model.
 */
private boolean isBindingCandidate(String attributeName, Object value) {
	if (attributeName.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
		return false;
	}

	Class<?> attrType = (value != null) ? value.getClass() : null;
	if (this.sessionAttributesHandler.isHandlerSessionAttribute(attributeName, attrType)) {
		return true;
	}

	return (value != null && !value.getClass().isArray() && !(value instanceof Collection) &&
			!(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass()));
}
 
Example 39
Project: YiDu-Novel   File: BlockEditAction.java   Source Code and License 5 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    // 初始化下拉列表选项
    initCollections(new String[] { "collectionProperties.article.category", "collectionProperties.block.type",
            "collectionProperties.block.target", "collectionProperties.block.sortCol",
            "collectionProperties.boolean" });
    // 编辑
    if (blockno != 0) {
        TSystemBlock systemBlock = systemBlockService.getByNo(blockno);
        BeanUtils.copyProperties(systemBlock, this);
    }
    logger.debug("loadData normally end.");
}
 
Example 40
Project: spring-backend-boilerplate   File: AuditEventPersisterImpl.java   Source Code and License 5 votes vote down vote up
@Override
public AuditEvent saveAuditEvent(in.clouthink.daas.audit.core.AuditEvent o) {
	AuditEvent auditEvent = new AuditEvent();
	BeanUtils.copyProperties(o, auditEvent);
	if (o.getRequestedBy() != null) {
		auditEvent.setRequestedBy(o.getRequestedBy().toString());
	}
	auditEvent.setRealm("backend");
	return auditEventRepository.save(auditEvent);
}
 
Example 41
Project: YiDu-Novel   File: ChapterListAction.java   Source Code and License 5 votes vote down vote up
@Override
protected void loadData() {
    if (articleno == 0) {
        addActionError(getText("errors.required.input",
                new String[] { getText("label.admin.chapter.list.articleno") }));
    }
    article = articleService.getByNo(articleno);
    ChapterSearchBean searchBean = new ChapterSearchBean();
    BeanUtils.copyProperties(this, searchBean);
    searchBean.setPagination(null);
    chapterList = chapterService.find(searchBean);
}
 
Example 42
Project: FCat   File: TElementServiceImpl.java   Source Code and License 5 votes vote down vote up
@Cacheable(value = "telement_role", key = "'role_element_'+#role")
public List<TElementVo> getListByRole(String role) {
    List<TElementVo> resultList = new ArrayList<>();
    List<TElement> tElements = mapper.getListByRole(role);
    tElements.forEach(tElement -> {
        TElementVo tElementVo = new TElementVo();
        BeanUtils.copyProperties(tElement,tElementVo);
        resultList.add(tElementVo);
    });
    return resultList;
}
 
Example 43
Project: admin-shiro   File: AdminService.java   Source Code and License 5 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void addAdmin(AdminAddAO ao) {
    AdminDO adminDO = new AdminDO();
    BeanUtils.copyProperties(ao, adminDO);
    RoleDO roleDO = daoSupport.get(ao.getRoleId(), RoleDO.class);
    adminDO.setPassword(PasswordUtil.createAdminPwd(adminDO.getPassword(), adminDO.getCredentialsSalt()));
    adminDO.setUid(String.valueOf(snowflakeIdWorker.nextId()));
    adminDO.setRole(roleDO);
    daoSupport.save(adminDO);
}
 
Example 44
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: RestaurantController.java   Source Code and License 5 votes vote down vote up
/**
 * Add restaurant with the specified information.
 *
 * @param restaurantVO
 * @return A non-null restaurant.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Restaurant> add(@RequestBody RestaurantVO restaurantVO) {
    logger.info(String.format("restaurant-service add() invoked: %s for %s", restaurantService.getClass().getName(), restaurantVO.getName()));
    System.out.println(restaurantVO);
    Restaurant restaurant = new Restaurant(null, null, null, null);
    BeanUtils.copyProperties(restaurantVO, restaurant);
    try {
        restaurantService.add(restaurant);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Restaurant REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
Example 45
Project: lams   File: SimpleInstantiationStrategy.java   Source Code and License 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (beanDefinition.getMethodOverrides().isEmpty()) {
		Constructor<?> constructorToUse;
		synchronized (beanDefinition.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = beanDefinition.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
							@Override
							public Constructor<?> run() throws Exception {
								return clazz.getDeclaredConstructor((Class[]) null);
							}
						});
					}
					else {
						constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
					}
					beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Exception ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		return instantiateWithMethodInjection(beanDefinition, beanName, owner);
	}
}
 
Example 46
Project: docs-manage   File: DirectoryController.java   Source Code and License 5 votes vote down vote up
/**
 * DocumentList转成DocumentDTOList
 * @param documentList documentList
 * @return documentDTOList
 */
private List<DocumentDTO> transferDocument(List<Document> documentList) {
    return documentList.stream().map(document -> {
        DocumentDTO documentDTO = new DocumentDTO();
        BeanUtils.copyProperties(document, documentDTO);
        return documentDTO;
    }).collect(Collectors.toList());
}
 
Example 47
Project: YiDu-Novel   File: UserEditAction.java   Source Code and License 5 votes vote down vote up
@Override
protected void loadData() {
    logger.debug("loadData start.");
    int userno = LoginManager.getLoginUser().getUserno();
    // 初始化类别下拉列表选项
    initCollections(new String[] { "collectionProperties.user.sex", "collectionProperties.user.type" });
    // 编辑
    TUser user = userService.getByNo(userno);
    BeanUtils.copyProperties(user, this);

    logger.debug("loadData normally end.");
}
 
Example 48
Project: lams   File: ServiceLocatorFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * Create a service locator exception for the given cause.
 * Only called in case of a custom service locator exception.
 * <p>The default implementation can handle all variations of
 * message and exception arguments.
 * @param exceptionConstructor the constructor to use
 * @param cause the cause of the service lookup failure
 * @return the service locator exception to throw
 * @see #setServiceLocatorExceptionClass
 */
protected Exception createServiceLocatorException(Constructor<Exception> exceptionConstructor, BeansException cause) {
	Class<?>[] paramTypes = exceptionConstructor.getParameterTypes();
	Object[] args = new Object[paramTypes.length];
	for (int i = 0; i < paramTypes.length; i++) {
		if (paramTypes[i].equals(String.class)) {
			args[i] = cause.getMessage();
		}
		else if (paramTypes[i].isInstance(cause)) {
			args[i] = cause;
		}
	}
	return BeanUtils.instantiateClass(exceptionConstructor, args);
}
 
Example 49
Project: dubbo-transaction   File: TransactionContextFactory.java   Source Code and License 5 votes vote down vote up
public  TransactionContextFactory  start(){
    if(contexts.isEmpty() && state.compareAndSet(false,true)){
        Class tcClass = TransactionConfig.getInstance().contextClass2Class();
        tcCount = TransactionConfig.getInstance().contextCount2Int();
        Assert.isTrue(null != tcClass && TransactionContext.class.isAssignableFrom(tcClass), "tcClass is null or not assignable from TransactionContext");
        for (int i = 0; i < tcCount; i++) {
            TransactionContext tc = (TransactionContext) BeanUtils.instantiateClass(tcClass);
            contexts.add(tc);
        }
    }
    return this;
}
 
Example 50
Project: lams   File: CglibSubclassingInstantiationStrategy.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
Object instantiate(Constructor<?> ctor, Object[] args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);

	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception e) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
				"Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
		}
	}

	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
		new LookupOverrideMethodInterceptor(beanDefinition, owner),//
		new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });

	return instance;
}
 
Example 51
Project: FCat   File: TUserServiceRpc.java   Source Code and License 5 votes vote down vote up
/**
 * 通过用户名获取用户的基本信息
 * @param userName
 * @return
 */
@RequestMapping(value = "/user/username/{userName}", method = RequestMethod.POST)
public com.xfdmao.fcat.api.vo.user.TUser getByUsername(@PathVariable("userName") String userName) {
	com.xfdmao.fcat.api.vo.user.TUser tUser = null;
	try {
		TUser tUser1 = tUserService.getByUsername(userName);
		if (tUser1 != null) {
			tUser=new com.xfdmao.fcat.api.vo.user.TUser();
			BeanUtils.copyProperties(tUser1,tUser);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return tUser;
}
 
Example 52
Project: sell   File: OrderServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public OrderDto finish(OrderDto orderDto) {

    // 判断订单状态
    if (!orderDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
        log.error("【完结订单】订单状态不正确,orderId={}, orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus());
        throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
    }

    // 修改订单状态
    orderDto.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
    OrderMaster orderMaster = new OrderMaster();
    BeanUtils.copyProperties(orderDto, orderMaster);
    OrderMaster updateResult = orderMasterRepository.save(orderMaster);
    if (updateResult == null) {
        log.error("【完结订单】更新失败,orderMaster={}", orderMaster);
        throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
    }

    return orderDto;
}
 
Example 53
Project: FastBootWeixin   File: WxWebConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public WxSessionManager wxSessionManager() {
    return new DefaultWxSessionManager(wxProperties.getServer().getSessionTimeout(),
            wxProperties.getServer().getMaxActiveLimit(),
            BeanUtils.instantiate(wxProperties.getServer().getWxSessionIdGeneratorClass()));
}
 
Example 54
Project: sjk   File: MergeServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public App createAppFromMarketApp(MarketApp mApp, Session session, Date now) throws Exception {
    final App newApp = new App();
    // init
    BeanUtils.copyProperties(mApp, newApp, ignoreProperties);
    if (mApp.getIndexImgUrl() == null) {
        newApp.setIndexImgUrl("");
    }
    if (mApp.getLanguage() == null) {
        newApp.setLanguage("");
    }
    // 新增的. 确保JVM不对初始值的影响
    newApp.setId(null);
    newApp.setAutoCover(true);
    // convert catalog infos
    convertCatalogForApp(session, mApp, newApp, false);
    // set forginer key
    newApp.setMarketAppId(mApp.getId());
    setOfficialSigSha1ByPkname(session, newApp);
    newApp.setStatus(AppStatus.ADD.getVal());
    // all properties , datetime
    newApp.setApkScanTime(mApp.getMarketApkScanTime());
    newApp.setLastFetchTime(now);
    appDao.save(session, newApp);
    mApp.setAppFetchTime(now);
    marketAppDao.update(session, mApp);

    // 为索引历史表 准备
    appHistory4IndexDaoImpl.saveOrUpdate(newApp.getId());
    return newApp;
}
 
Example 55
Project: spring-jdbc-orm   File: SingleTableEntityPersister.java   Source Code and License 5 votes vote down vote up
/**
 *
 * 初始化字段分表信息
 * @param field 字段
 */
private void initSplitTable(Field field){
    SplitTableField splitTable = field.getAnnotation(SplitTableField.class);
    if (null != splitTable){
        splitTableDescriptor = new SplitTableDescriptor();
        splitTableDescriptor.setField(field.getName());
        splitTableDescriptor.setHandler(BeanUtils.<TableHandler>instantiateClass(splitTable.handler()));
        splitTableDescriptor.setPrefix(splitTable.prefix() ?  (tableName + "_") : "" );
    }
}
 
Example 56
Project: spring-boot-start-current   File: PermissionResourceServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@CacheEvict( value = GlobalCacheConstant.USER_DETAILS_SERVICE_NAMESPACE, allEntries = true, condition = "#result != null" )
public boolean update ( PermissionResourceForm form ) {
	PermissionResource permissionResource = new PermissionResource();
	BeanUtils.copyProperties( form , permissionResource );
	apiHandle( form , permissionResource );
	return super.updateById( permissionResource );
}
 
Example 57
Project: exam   File: RoomController.java   Source Code and License 5 votes vote down vote up
@Restrict(@Group({"ADMIN"}))
public Result updateExamRoomWorkingHours() {
    JsonNode root = request().body().asJson();
    List<Long> roomIds = new ArrayList<>();
    for (JsonNode roomId : root.get("roomIds")) {
        roomIds.add(roomId.asLong());
    }
    List<ExamRoom> rooms = Ebean.find(ExamRoom.class).where().idIn(roomIds).findList();
    List<DefaultWorkingHours> blueprints = parseWorkingHours(root);
    for (ExamRoom examRoom : rooms) {
        List<DefaultWorkingHours> previous = examRoom.getDefaultWorkingHours();
        Ebean.deleteAll(previous);
        previous.clear();
        for (DefaultWorkingHours blueprint : blueprints) {
            DefaultWorkingHours copy = new DefaultWorkingHours();
            BeanUtils.copyProperties(blueprint, copy, "id", "room");
            copy.setRoom(examRoom);
            DateTime end = new DateTime(blueprint.getEndTime());
            int offset = DateTimeZone.forID(examRoom.getLocalTimezone()).getOffset(end);
            int endMillisOfDay = DateTimeUtils.resolveEndWorkingHourMillis(end, offset) - offset;
            copy.setEndTime(end.withMillisOfDay(endMillisOfDay));
            copy.setTimezoneOffset(offset);
            copy.save();
            previous.add(copy);
        }
        asyncUpdateRemote(examRoom);
    }
    return ok();
}
 
Example 58
Project: spring-boot-jwt-jpa   File: DailyCategoryService.java   Source Code and License 5 votes vote down vote up
public Long add(DailyCategoryReq req) {
    DailyCategory dailyCategory = new DailyCategory();
    BeanUtils.copyProperties(req, dailyCategory);
    dailyCategory.setStatus(ItemStatus.NORMAL.getStatus());
    Date now = new Date();
    dailyCategory.setCreatedTime(now);
    dailyCategory.setUpdatedTime(now);

    DailyCategory save = dailyCategoryRepository.save(dailyCategory);
    return save.getId();
}
 
Example 59
Project: spring-boot-jwt-jpa   File: ReviewsService.java   Source Code and License 5 votes vote down vote up
public List<ReviewsRes> getReviews(ReviewsReq vo) {
    List<Reviews> reviewsList = reviewsRepository.findByAppOrderByRetrievedDateDesc(vo.getApp());
    if (reviewsList.isEmpty()) {
        Apps apps = new Apps();
        apps.setId(vo.getApp());
        long count = appsRepository.count(Example.of(apps));
        if (count == 0) {
            apps.setEnabled(true);
            apps.setName("");
            apps.setIphone(false);
            apps.setIpad(false);
            apps.setOsx(false);
            appsRepository.saveAndFlush(apps);
        } else {
            LOGGER.info("do nothing.appId:{} already exists.", vo.getApp());
        }
        return newArrayList();
    }
    List<ReviewsRes> resList = new ArrayList<>(reviewsList.size());
    for (Reviews reviews : reviewsList) {
        ReviewsRes res = new ReviewsRes();
        BeanUtils.copyProperties(reviews, res);
        res.setRetrievedDate(reviews.getRetrievedDate().getTime());
        resList.add(res);
    }
    return resList;
}
 
Example 60
Project: SpringBoot_Wechat_Sell   File: OrderServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public OrderDTO paid(OrderDTO orderDTO) {


    if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
        log.error("【支付订单操作】 订单状态不正确 orderId={},orderStats={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
        throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
    }


    if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
        log.error("【支付订单操作】 订单支付状态不正确 orderId={},orderStats={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
        throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
    }

    //修改支付状态
    orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
    OrderMaster orderMaster = new OrderMaster();
    BeanUtils.copyProperties(orderDTO, orderMaster);

    OrderMaster updateResult = orderMasterRepository.save(orderMaster);

    if (updateResult == null) {
        log.error("支付订单失败,orderMaster={}", orderMaster);
        throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
    }
    return orderDTO;
}