org.modelmapper.ModelMapper Java Examples
The following examples show how to use
org.modelmapper.ModelMapper.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModelMapperItemProcessor.java From incubator-batchee with Apache License 2.0 | 7 votes |
private ModelMapper ensureMapper() { if (mapper == null) { synchronized (this) { if (mapper == null) { mapper = newMapper(); if (matchingStrategy != null) { final Configuration configuration = mapper.getConfiguration(); try { configuration.setMatchingStrategy(MatchingStrategy.class.cast( MatchingStrategies.class.getDeclaredField(matchingStrategy.toUpperCase(Locale.ENGLISH)).get(null))); } catch (final Exception e) { try { configuration.setMatchingStrategy(MatchingStrategy.class.cast(currentLoader().loadClass(matchingStrategy))); } catch (final Exception e1) { if (RuntimeException.class.isInstance(e)) { throw RuntimeException.class.cast(e); } throw new IllegalStateException(e); } } } } } } return mapper; }
Example #2
Source File: ConvertUtils.java From agile-service-old with Apache License 2.0 | 6 votes |
public static StateMachineSchemeVO convertStateMachineSchemeToVO(final StateMachineSchemeDTO scheme, final Map<Long, ProjectVO> projectMap) { ModelMapper modelMapper = new ModelMapper(); StateMachineSchemeVO schemeVO = modelMapper.map(scheme, StateMachineSchemeVO.class); List<StateMachineSchemeConfigDTO> schemeConfigs = scheme.getSchemeConfigs(); if (null != schemeConfigs && !schemeConfigs.isEmpty()) { List<StateMachineSchemeConfigVO> schemeConfigVOS = modelMapper.map(schemeConfigs, new TypeToken<List<StateMachineSchemeConfigVO>>() { }.getType()); schemeVO.setConfigVOS(schemeConfigVOS); } List<ProjectConfigDTO> projectConfigs = scheme.getProjectConfigs(); if (null != projectConfigs && !projectConfigs.isEmpty()) { List<ProjectVO> projectVOS = new ArrayList<>(projectConfigs.size()); for (ProjectConfigDTO config : projectConfigs) { ProjectVO projectVO = projectMap.get(config.getProjectId()); if (projectVO != null) { projectVOS.add(projectVO); } } schemeVO.setProjectVOS(projectVOS); } return schemeVO; }
Example #3
Source File: MediaEntityToMediaDtoTest.java From jwala with Apache License 2.0 | 6 votes |
@Test public void testMediaEntityToMediaDto() throws Exception { final JpaMedia jpaMedia = new JpaMedia(); jpaMedia.setId(1L); jpaMedia.setName("JDK Lite"); jpaMedia.setType(MediaType.JDK); jpaMedia.setLocalPath(Paths.get("localPath")); jpaMedia.setRootDir(Paths.get("mediaDir")); jpaMedia.setRemoteDir(Paths.get("remoteDir")); final Media media = new ModelMapper().map(jpaMedia, Media.class); assertEquals(1L, media.getId().longValue()); assertEquals("JDK Lite", media.getName()); assertEquals(MediaType.JDK, media.getType()); assertEquals("localPath", media.getLocalPath().toString()); assertEquals("mediaDir", media.getRootDir().toString()); assertEquals("remoteDir", media.getRemoteDir().toString()); }
Example #4
Source File: AccountServiceTest.java From staffjoy with MIT License | 6 votes |
@Test public void testModelMapper() { ModelMapper modelMapper = new ModelMapper(); Account account = Account.builder().id("123456") .name("testAccount") .email("[email protected]") .memberSince(Instant.now()) .confirmedAndActive(true) .photoUrl("https://staffjoy.xyz/photo/test.png") .phoneNumber("18001801266") .support(false) .build(); AccountDto accountDto = modelMapper.map(account, AccountDto.class); validateAccount(accountDto, account); Account account1 = modelMapper.map(accountDto, Account.class); validateAccount(accountDto, account1); }
Example #5
Source File: ModelMappingConfig.java From production-ready-microservices-starter with MIT License | 6 votes |
private void addMappingSiteCreateUpdateRequestToSite(ModelMapper mapper) { PropertyMap propertyMap = new PropertyMap<SiteCreateUpdateRequest, Site>() { @Override protected void configure() { skip(destination.getId()); skip(destination.getCreatedBy()); skip(destination.getUpdatedBy()); skip(destination.getCreatedAt()); skip(destination.getUpdatedAt()); skip(destination.getOrg()); skip(destination.getTenant()); } }; mapper.createTypeMap(SiteCreateUpdateRequest.class, Site.class).addMappings(propertyMap); mapper.validate(); }
Example #6
Source File: MdcExceptionLogServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override public void saveAndSendExceptionLog(final GlobalExceptionLogDto exceptionLogDto) { MdcExceptionLog exceptionLog = new ModelMapper().map(exceptionLogDto, MdcExceptionLog.class); exceptionLog.setId(generateId()); exceptionLog.setCreateTime(new Date()); mdcExceptionLogMapper.insertSelective(exceptionLog); taskExecutor.execute(() -> { if (judgeIsSend(exceptionLogDto.getProfile())) { String text = exceptionLog.getApplicationName() + "出现异常. 环境:" + exceptionLogDto.getProfile() + ",操作人:" + exceptionLogDto.getCreator() + ".异常类型:" + exceptionLogDto.getExceptionSimpleName(); ChatRobotMsgDto chatRobotMsgDto = ChatRobotMsgFactory.createChatRobotTextMsg(webhookToken, text, false, null); opcRpcService.sendChatRobotMsg(chatRobotMsgDto); } }); }
Example #7
Source File: MdcDictServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override @Transactional(readOnly = true, rollbackFor = Exception.class) public MdcDictVo getMdcDictVoById(Long dictId) { MdcDict dict = mdcDictMapper.selectByPrimaryKey(dictId); if (dict == null) { logger.error("找不到数据字典信息id={}", dictId); throw new MdcBizException(ErrorCodeEnum.MDC10021018, dictId); } // 获取父级菜单信息 MdcDict parentDict = mdcDictMapper.selectByPrimaryKey(dict.getPid()); ModelMapper modelMapper = new ModelMapper(); MdcDictVo dictVo = modelMapper.map(dict, MdcDictVo.class); if (parentDict != null) { dictVo.setParentDictName(parentDict.getDictName()); } return dictVo; }
Example #8
Source File: MdcProductCategoryServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override public MdcCategoryVo getMdcCategoryVoById(final Long categoryId) { MdcProductCategory category = mdcProductCategoryMapper.selectByPrimaryKey(categoryId); if (category == null) { logger.error("找不到数据字典信息id={}", categoryId); throw new MdcBizException(ErrorCodeEnum.MDC10023001, categoryId); } // 获取父级菜单信息 MdcProductCategory parentCategory = mdcProductCategoryMapper.selectByPrimaryKey(category.getPid()); ModelMapper modelMapper = new ModelMapper(); MdcCategoryVo categoryVo = modelMapper.map(category, MdcCategoryVo.class); categoryVo.setId(category.getId()); categoryVo.setPid(category.getPid()); if (parentCategory != null) { categoryVo.setParentCategoryName(parentCategory.getName()); } return categoryVo; }
Example #9
Source File: MdcProductServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override public ProductVo getProductVo(final Long id) { MdcProduct mdcProduct = mdcProductMapper.selectByPrimaryKey(id); ProductVo productVo = new ModelMapper().map(mdcProduct, ProductVo.class); List<Long> categoryIdList = Lists.newArrayList(); buildCategoryIdList(categoryIdList, mdcProduct.getCategoryId()); // 获取分类节点集合 Collections.reverse(categoryIdList); productVo.setCategoryIdList(categoryIdList); // 获取图片集合 final OptBatchGetUrlRequest request = new OptBatchGetUrlRequest(mdcProduct.getProductCode()); request.setEncrypt(true); List<ElementImgUrlDto> imgUrlList = opcRpcService.listFileUrl(request); productVo.setImgUrlList(imgUrlList); return productVo; }
Example #10
Source File: EventFilterConfiguration.java From eventeum with Apache License 2.0 | 6 votes |
public List<ContractEventFilter> getConfiguredEventFilters() { List<ContractEventFilter> filtersToReturn = new ArrayList<>(); if (eventFilters != null) { final ModelMapper mapper = ModelMapperFactory.getInstance().createModelMapper(); eventFilters.forEach((configFilter) -> { final ContractEventFilter contractEventFilter = new ContractEventFilter(); mapper.map(configFilter, contractEventFilter); contractEventFilter.setContractAddress(Keys.toChecksumAddress(contractEventFilter.getContractAddress())); contractEventFilter.setCorrelationIdStrategy(configFilter.getCorrelationId().toStrategy()); contractEventFilter.setContractAddress(Keys.toChecksumAddress(contractEventFilter.getContractAddress())); filtersToReturn.add(contractEventFilter); }); } return filtersToReturn; }
Example #11
Source File: UacMenuServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override @Transactional(readOnly = true, rollbackFor = Exception.class) public ViewMenuVo getViewVoById(Long id) { Preconditions.checkArgument(id != null, "菜单ID不能为空"); UacMenu menu = uacMenuMapper.selectByPrimaryKey(id); if (menu == null) { logger.error("找不到菜单信息id={}", id); throw new UacBizException(ErrorCodeEnum.UAC10013003, id); } // 获取父级菜单信息 UacMenu parentMenu = uacMenuMapper.selectByPrimaryKey(menu.getPid()); ModelMapper modelMapper = new ModelMapper(); ViewMenuVo menuVo = modelMapper.map(menu, ViewMenuVo.class); if (parentMenu != null) { menuVo.setParentMenuName(parentMenu.getMenuName()); } return menuVo; }
Example #12
Source File: UacLogServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override public Integer saveOperationLog(OperationLogDto operationLogDto) { // 根据uri 查询url对应的权限 UacAction uacAction = uacActionService.matchesByUrl(operationLogDto.getRequestUrl()); if (uacAction != null) { operationLogDto.setActionCode(uacAction.getActionCode()); operationLogDto.setActionName(uacAction.getActionName()); operationLogDto.setActionId(uacAction.getId()); } ModelMapper modelMapper = new ModelMapper(); UacLog uacLog = modelMapper.map(operationLogDto, UacLog.class); uacLog.setId(generateId()); // 获取操作位置 String locationById = opcRpcService.getLocationById(operationLogDto.getIp()); uacLog.setLocation(locationById); return uacLogMapper.insertSelective(uacLog); }
Example #13
Source File: Web3jBlock.java From eventeum with Apache License 2.0 | 6 votes |
public Web3jBlock(EthBlock.Block web3jBlock, String nodeName) { final ModelMapper modelMapper = ModelMapperFactory.getInstance().createModelMapper(); modelMapper.typeMap( EthBlock.Block.class, Web3jBlock.class) .addMappings(mapper -> { mapper.skip(Web3jBlock::setTransactions); //Nonce can be null which throws exception in web3j when //calling getNonce (because of attempted hex conversion) if (web3jBlock.getNonceRaw() == null) { mapper.skip(Web3jBlock::setNonce); } }); modelMapper.map(web3jBlock, this); transactions = convertTransactions(web3jBlock.getTransactions()); this.nodeName = nodeName; }
Example #14
Source File: TpcMqMessageServiceImpl.java From paascloud-master with Apache License 2.0 | 6 votes |
@Override public void saveAndSendMessage(TpcMqMessageDto tpcMqMessageDto) { if (StringUtils.isEmpty(tpcMqMessageDto.getMessageTopic())) { throw new TpcBizException(ErrorCodeEnum.TPC10050001); } Date now = new Date(); TpcMqMessage message = new ModelMapper().map(tpcMqMessageDto, TpcMqMessage.class); message.setMessageStatus(MqSendStatusEnum.SENDING.sendStatus()); message.setId(generateId()); message.setUpdateTime(now); message.setCreatedTime(now); tpcMqMessageMapper.insertSelective(message); // 创建消费待确认列表 this.createMqConfirmListByTopic(message.getMessageTopic(), message.getId(), message.getMessageKey()); this.directSendMessage(tpcMqMessageDto.getMessageBody(), tpcMqMessageDto.getMessageTopic(), tpcMqMessageDto.getMessageTag(), tpcMqMessageDto.getMessageKey(), tpcMqMessageDto.getProducerGroup(), tpcMqMessageDto.getDelayLevel()); }
Example #15
Source File: Web3jTransactionReceipt.java From eventeum with Apache License 2.0 | 5 votes |
public Web3jTransactionReceipt( org.web3j.protocol.core.methods.response.TransactionReceipt web3TransactionReceipt) { logs = convertLogs(web3TransactionReceipt.getLogs()); try { final ModelMapper modelMapper = ModelMapperFactory.getInstance().createModelMapper(); //Skip logs modelMapper.getConfiguration().setPropertyCondition(ctx -> !ctx.getMapping().getLastDestinationProperty().getName().equals("logs")); modelMapper.map(web3TransactionReceipt, this); } catch (RuntimeException re) { re.printStackTrace(); throw re; } }
Example #16
Source File: MappingConfig.java From production-ready-microservices-starter with MIT License | 5 votes |
@Bean public ModelMapper createModelMapper() { ModelMapper mapper = new ModelMapper(); mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); return mapper; }
Example #17
Source File: GroupManagerImpl.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
@Autowired public GroupManagerImpl(ModelMapper mapper, UserEntityRepository userEntityRepository, GroupEntityRepository groupEntityRepository, AuthorityEntityRepository authorityEntityRepository) { this.modelMapper = mapper; this.userEntityRepository = userEntityRepository; this.groupEntityRepository = groupEntityRepository; this.authorityEntityRepository = authorityEntityRepository; }
Example #18
Source File: GroupManagerImpl.java From webauthn4j-spring-security with Apache License 2.0 | 5 votes |
@Autowired public GroupManagerImpl(ModelMapper mapper, UserEntityRepository userEntityRepository, GroupEntityRepository groupEntityRepository, AuthorityEntityRepository authorityEntityRepository) { this.modelMapper = mapper; this.userEntityRepository = userEntityRepository; this.groupEntityRepository = groupEntityRepository; this.authorityEntityRepository = authorityEntityRepository; }
Example #19
Source File: UserRestController.java From spring-boot-doma2-sample with Apache License 2.0 | 5 votes |
/** * ユーザーを更新します。 * * @param */ @PutMapping(value = "/{userId}") public Resource update(@PathVariable("userId") Long userId, @Validated @RequestBody User inputUser, Errors errors) { // 入力エラーがある場合 if (errors.hasErrors()) { throw new ValidationErrorException(errors); } // 1件更新する inputUser.setId(userId); User user; { //TODO 本来ならサービスで実装すべき //created_byなどがAPIからは取得できないので、DBから取得して、パラメータで更新内容を上書きしている user = userService.findById(inputUser.getId()); ModelMapper modelMapper = DefaultModelMapperFactory.create(); modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull()); modelMapper.map(inputUser, user); } user = userService.update(user); Resource resource = resourceFactory.create(); resource.setData(Arrays.asList(user)); resource.setMessage(getMessage(MESSAGE_SUCCESS)); return resource; }
Example #20
Source File: ModelMapperAutoConfiguration.java From building-microservices with Apache License 2.0 | 5 votes |
private void addConverters(ModelMapper modelMapper) { if (this.properties.isAddConverters() && this.converters != null) { for (Converter<?, ?> converter : this.converters) { modelMapper.addConverter(converter); } } }
Example #21
Source File: TestModelMappings.java From dremio-oss with Apache License 2.0 | 5 votes |
/** * check to make sure both protobuf entities have same number of fields. */ @Test public void ensure1to1onAwsProps() { ModelMapper mapper = new ModelMapper(); mapper.registerModule(new ProtobufModule()); mapper.createTypeMap(AwsProps.class, AwsPropsApi.class); mapper.createTypeMap(AwsPropsApi.class, AwsProps.class); mapper.validate(); AwsPropsApi api = AwsPropsApi.builder().build(); @SuppressWarnings("unused") ImmutableAwsPropsApi ignored = mapper.map(mapper.map(api, AwsProps.class), ImmutableAwsPropsApi.Builder.class).build(); }
Example #22
Source File: OmcOrderServiceImpl.java From paascloud-master with Apache License 2.0 | 5 votes |
@Override public OrderDto queryOrderDtoByOrderNo(String orderNo) { OmcOrder omcOrder = this.queryByOrderNo(orderNo); if (omcOrder == null) { throw new OmcBizException(ErrorCodeEnum.OMC10031005, orderNo); } ModelMapper modelMapper = new ModelMapper(); return modelMapper.map(omcOrder, OrderDto.class); }
Example #23
Source File: DefaultModelMapperFactory.java From spring-boot-doma2-sample with Apache License 2.0 | 5 votes |
/** * ModelMapperを返します。 * * @return */ public static ModelMapper create() { // ObjectMappingのためのマッパー val modelMapper = new ModelMapper(); val configuration = modelMapper.getConfiguration(); configuration.setPropertyCondition( // IDフィールド以外をマッピングする context -> { // DomaDtoのIDカラムは上書きしないようにする PropertyInfo propertyInfo = context.getMapping().getLastDestinationProperty(); return !(context.getParent().getDestination() instanceof DomaDto && propertyInfo.getName().equals("id")); }); // 厳格にマッピングする configuration.setMatchingStrategy(MatchingStrategies.STRICT); // コンバーター val idToInt = new AbstractConverter<ID<?>, Integer>() { @Override protected Integer convert(ID<?> source) { return source == null ? null : source.getValue(); } }; modelMapper.addConverter(idToInt); return modelMapper; }
Example #24
Source File: TpcMqMessageServiceImpl.java From paascloud-master with Apache License 2.0 | 5 votes |
@Override public void saveMessageWaitingConfirm(TpcMqMessageDto messageDto) { if (StringUtils.isEmpty(messageDto.getMessageTopic())) { throw new TpcBizException(ErrorCodeEnum.TPC10050001); } Date now = new Date(); TpcMqMessage message = new ModelMapper().map(messageDto, TpcMqMessage.class); message.setMessageStatus(MqSendStatusEnum.WAIT_SEND.sendStatus()); message.setUpdateTime(now); message.setCreatedTime(now); tpcMqMessageMapper.insertSelective(message); }
Example #25
Source File: MallUserController.java From paascloud-master with Apache License 2.0 | 5 votes |
/** * 更新用户信息. * * @param userInfoDto the user info dto * * @return the wrapper */ @PostMapping(value = "/updateInformation") @ApiOperation(httpMethod = "POST", value = "更新用户信息") public Wrapper<UserInfoDto> updateInformation(@RequestBody UserInfoDto userInfoDto) { logger.info("updateInformation - 更新用户基本信息 userInfoDto={}", userInfoDto); UacUser uacUser = new ModelMapper().map(userInfoDto, UacUser.class); uacUserService.updateUser(uacUser); return WrapMapper.ok(); }
Example #26
Source File: UacUserTokenServiceImpl.java From paascloud-master with Apache License 2.0 | 5 votes |
@Override public UserTokenDto getByAccessToken(String accessToken) { UserTokenDto userTokenDto = (UserTokenDto) redisTemplate.opsForValue().get(RedisKeyUtil.getAccessTokenKey(accessToken)); if (userTokenDto == null) { UacUserToken uacUserToken = new UacUserToken(); uacUserToken.setAccessToken(accessToken); uacUserToken = uacUserTokenMapper.selectOne(uacUserToken); userTokenDto = new ModelMapper().map(uacUserToken, UserTokenDto.class); } return userTokenDto; }
Example #27
Source File: GenericConverter.java From heimdall with Apache License 2.0 | 5 votes |
/** * Converts a source to a type destination. * * @param source The souce object * @return The object created */ public static <E, T> List<E> mapper(List<T> source, Type destinationType) { List<E> model = null; if (source != null && destinationType != null) { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); model = modelMapper.map(source, destinationType); } return model; }
Example #28
Source File: GenericConverter.java From heimdall with Apache License 2.0 | 5 votes |
public static <T, E> void convertWithMapping(T source, E destination, PropertyMap<T, E> mapping) { if (source != null && destination != null) { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); modelMapper.addMappings(mapping); modelMapper.map(source, destination); } }
Example #29
Source File: OrderMapper.java From research-graphql with MIT License | 5 votes |
public OrderMapper() { mapper = new ModelMapper(); // use strict to prevent over eager matching (happens with ID fields) mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); // create PropertyMap<source,target> here and add to mapper mapper.addMappings(new PropertyMap<OrderForm, OrderDto>() { @Override protected void configure() { } }); mapper.addMappings(new PropertyMap<OrderDto, OrderForm>() { @Override protected void configure() { } }); mapper.addMappings(new PropertyMap<OrderItemDto, OrderItem>() { @Override protected void configure() { } }); // need to add the parent link to jpa order items (as these don't exist in dto form) mapper.getTypeMap(OrderDto.class, OrderForm.class) .setPostConverter(context -> { OrderForm target = context.getDestination(); log.info("post-converter fixing OrderItem parent links {}", target); if (target.getItems() != null) { target.getItems().stream().forEach((item) -> item.setOrder(target)); } return target; }); }
Example #30
Source File: ApplicationTestConfiguration.java From research-graphql with MIT License | 5 votes |
@Bean @Primary ProductAdaptor getProductAdaptor() { ProductAdaptor mock = mock(ProductAdaptor.class); when(mock.getAllProducts()) .thenReturn(new ArrayList<>(mapProducts.values())); when(mock.getProduct(anyString())) .then((inv) -> mapProducts.get(inv.getArgumentAt(0, String.class))); when(mock.upsertProduct(anyObject())) .then((inv) -> { ProductDto product = inv.getArgumentAt(0, ProductDto.class); ProductDto newProduct = new ModelMapper().map(product, ProductDto.class); if(newProduct.getId()==null) newProduct.setId(UUID.randomUUID().toString()); mapProducts.put(newProduct.getId(),newProduct); log.info("upsertProduct({}) : {}", product, newProduct); return newProduct; }); when(mock.deleteProduct(anyString())) .then((inv) -> { String productId = inv.getArgumentAt(0, String.class); ProductDto removedProduct = mapProducts.remove(productId); log.info("deleteProduct({}) : {}", productId, removedProduct); return removedProduct; }); return mock; }