Java Code Examples for org.modelmapper.ModelMapper#map()

The following examples show how to use org.modelmapper.ModelMapper#map() . 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: UacLogServiceImpl.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: GenericResultSetMapper.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  ModelMapper mapper = new ModelMapper();
  Map<String, Object> result = new HashMap<>();
  //[{jobName=Test_Anomaly_Task, jobId=1, workerId=1, taskType=MONITOR, id=1, taskInfo=clob2: '{"jobExecutionId":1,"monitorType":"UPDATE","expireDaysAgo":0}', lastModified=2016-08-24 17:25:53.258, version=0, taskStartTime=1470356753227, status=RUNNING, taskEndTime=1471220753227}]

  result.put("jobName", "Test_Anomaly_Task");
  result.put("jobId", 1L);
  result.put("taskType", "MONITOR");
  result.put("id", 1L);
  result.put("taskInfo",
      "clob2: '{\"jobExecutionId\":1,\"monitorType\":\"UPDATE\",\"expireDaysAgo\":0}'");
  result.put("taskType", "MONITOR");
  result.put("lastModified", "2016-08-24 17:25:53.258");
  result.put("status", "RUNNING");
  result.put("lastModified", "2016-08-24 17:25:53.258");
  TaskDTO taskSpec1 = mapper.map(result, TaskDTO.class);
  System.out.println(taskSpec1);

  //INPUT 2
  ObjectInputStream ois =
      new ObjectInputStream(new FileInputStream(new File("/tmp/map.out.1472093046128")));
  Map<String, Object> inputMap = (Map<String, Object>) ois.readObject();
  TaskDTO taskSpec2 = mapper.map(inputMap, TaskDTO.class);
  System.out.println(taskSpec2);
}
 
Example 3
Source File: MdcDictServiceImpl.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: UacMenuServiceImpl.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: AccountServiceTest.java    From staffjoy with MIT License 6 votes vote down vote up
@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 6
Source File: ConvertUtils.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
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 7
Source File: Web3jBlock.java    From eventeum with Apache License 2.0 6 votes vote down vote up
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 8
Source File: OmcOrderFeignClient.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
@ApiOperation(httpMethod = "POST", value = "更新订单信息")
public Wrapper updateOrderById(@RequestBody OrderDto orderDto) {
	logger.info("updateOrderById - 更新订单信息. orderDto={}", orderDto);
	ModelMapper modelMapper = new ModelMapper();
	OmcOrder omcOrder = modelMapper.map(orderDto, OmcOrder.class);
	int updateResult = omcOrderService.update(omcOrder);
	return handleResult(updateResult);

}
 
Example 9
Source File: PtcAlipayServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public Wrapper aliPayCallback(Map<String, String> params) {
	log.info("支付宝回调. - aliPayCallback. params={}", params);
	String orderNo = params.get("out_trade_no");
	String tradeNo = params.get("trade_no");
	String tradeStatus = params.get("trade_status");
	OrderDto order = omcOrderService.queryOrderDtoByOrderNo(orderNo);
	if (order == null) {
		throw new OmcBizException(ErrorCodeEnum.OMC10031010);
	}
	if (order.getStatus() >= OmcApiConstant.OrderStatusEnum.PAID.getCode()) {
		throw new OmcBizException(ErrorCodeEnum.OMC10031011);
	}
	if (PtcApiConstant.AlipayCallback.TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)) {
		order.setPaymentTime(DateUtil.parseDate(params.get("gmt_payment")));
		order.setStatus(OmcApiConstant.OrderStatusEnum.PAID.getCode());
		ModelMapper modelMapper = new ModelMapper();
		OmcOrder omcOrder = modelMapper.map(order, OmcOrder.class);
		omcOrderService.update(omcOrder);
	}

	PtcPayInfo payInfo = new PtcPayInfo();
	payInfo.setUserId(order.getUserId());
	payInfo.setOrderNo(order.getOrderNo());
	payInfo.setPayPlatform(PtcApiConstant.PayPlatformEnum.ALIPAY.getCode());
	payInfo.setPlatformNumber(tradeNo);
	payInfo.setPlatformStatus(tradeStatus);
	payInfo.setUpdateTime(new Date());
	payInfo.setCreatedTime(new Date());
	payInfo.setCreator(order.getCreator());
	payInfo.setCreatorId(order.getUserId());
	payInfo.setLastOperator(order.getLastOperator());
	payInfo.setLastOperatorId(order.getLastOperatorId());
	payInfo.setId(UniqueIdGenerator.generateId());

	ptcPayInfoMapper.insertSelective(payInfo);

	return WrapMapper.ok();
}
 
Example 10
Source File: OmcOrderServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: OmcOrderServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public OrderDto queryOrderDtoByUserIdAndOrderNo(Long userId, String orderNo) {
	OmcOrder omcOrder = this.queryByUserIdAndOrderNo(userId, orderNo);
	if (omcOrder == null) {
		throw new OmcBizException(ErrorCodeEnum.OMC10031005, orderNo);
	}
	ModelMapper modelMapper = new ModelMapper();
	return modelMapper.map(omcOrder, OrderDto.class);
}
 
Example 12
Source File: AbstractSpec.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static <T extends AbstractSpec> T fromProperties(Map<String, Object> properties, Class<T> specClass) {
  // don't reuse model mapper instance. It caches typeMaps and will result in unexpected mappings
  ModelMapper modelMapper = new ModelMapper();
  // use strict mapping to ensure no mismatches or ambiguity occurs
  modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
  return modelMapper.map(properties, specClass);
}
 
Example 13
Source File: Web3jTransactionReceipt.java    From eventeum with Apache License 2.0 5 votes vote down vote up
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 14
Source File: GenericConverter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
* Converts a source to a type destination.
* 
* @param source					The source object
* @param typeDestination			The type destination
* @return							The object created
*/
  public static <T, E> E mapper(T source, Class<E> typeDestination) {

       ModelMapper modelMapper = new ModelMapper();
       modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
       return modelMapper.map(source, typeDestination);

  }
 
Example 15
Source File: GenericConverter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a source to a type destination.
 *
 * @param source				The source object
 * @param destination			The destination object
 * @return						The object created
 */
public static <T, E> E mapper(T source, E destination) {

     ModelMapper modelMapper = new ModelMapper();
     modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
     modelMapper.map(source, destination);

     return destination;
}
 
Example 16
Source File: GenericConverter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * 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 17
Source File: GenericConverter.java    From heimdall with Apache License 2.0 5 votes vote down vote up
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 18
Source File: UserRestController.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * ユーザーを更新します。
 *
 * @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 19
Source File: Web3jLog.java    From eventeum with Apache License 2.0 4 votes vote down vote up
public Web3jLog(org.web3j.protocol.core.methods.response.Log web3jLog) {

        final ModelMapper modelMapper = ModelMapperFactory.getInstance().createModelMapper();
        modelMapper.map(web3jLog, this);
    }
 
Example 20
Source File: Web3jTransaction.java    From eventeum with Apache License 2.0 4 votes vote down vote up
public Web3jTransaction(org.web3j.protocol.core.methods.response.Transaction web3jTransaction) {

        final ModelMapper modelMapper = ModelMapperFactory.getInstance().createModelMapper();
        modelMapper.map(web3jTransaction, this);
    }