@Bean public Mapper fooDozerBeanMapper() { DozerBeanMapper mapper = BeanMapper.getDozerBeanMapper(); List<String> mappingFiles = new ArrayList(mapper.getMappingFiles()); mappingFiles.add("foo-dozer-custom-convert.xml"); mapper.setMappingFiles(mappingFiles); return mapper; }
public Destination convert(final Source source) { /* * CustomConverter converter = new CustomConverter(Source.class, * Target.class); Target target = converter.convertTo(source); */ DozerBeanMapper mapper = new DozerBeanMapper(); return mapper.map(source, Destination.class, ""); }
@Test public void testBeanMappingBuilder() throws Exception { DozerBeanMapper mapper = (DozerBeanMapper) context.getBean("factoryWithMappingBuilder", DozerBeanMapper.class); Source source = new Source(); source.setName("John"); source.setId(2L); Destination destination = mapper.map(source, Destination.class); assertEquals("John", destination.getValue()); assertEquals(2L, destination.getId()); }
@Test public void testInjectConverter() throws Exception { DozerBeanMapper mapper = context.getBean("mapperWithConverter", DozerBeanMapper.class); assertNotNull(mapper); assertNotNull(mapper.getMappingFiles()); List<CustomConverter> customConverters = mapper.getCustomConverters(); assertEquals(1, customConverters.size()); InjectedCustomConverter converter = context.getBean(InjectedCustomConverter.class); converter.setInjectedName("inject"); assertBasicMapping(mapper); }
public ShowDetailed get(String alias) { DBObject one = db.getCollection("show").findOne(aliasOrId(alias)); if (one == null) { throw new NotFoundException("No such show"); } ShowDetailed detailed = mapper.map(one, ShowDetailed.class); Date now = new Date(); for (SchedulingSimple ss : detailed.getSchedulings()) { if (ss.getValidFrom().compareTo(now) < 0 && ss.getValidTo().compareTo(now) > 0) ss.setText(schedulingTextUtil.create(ss)); } if (detailed.getContributors() != null) { for (ShowContribution contributor : detailed.getContributors()) { if (contributor.getAuthor() != null) { avatarLocator.locateAvatar(contributor.getAuthor()); } } } long mixCount = db.getCollection("mix") .count(new BasicDBObject("show.ref", new DBRef(db, "show", one.get("_id").toString()))); detailed.getStats().mixCount = (int) mixCount; detailed.setUrls(processUrls(detailed.getUrls())); return detailed; }
@Bean public Mapper dozerBeanMapper() { DozerBeanMapper dozerBeanMapper = new DozerBeanMapper(); BeanMappingBuilder builder = new BeanMappingBuilder() { protected void configure() { mapping(FacebookProfile.class, com.techlooper.entity.FacebookProfile.class) .fields( "locale", "locale", FieldsMappingOptions.customConverter(LocaleConverter.class)); } }; dozerBeanMapper.addMapping(builder); return dozerBeanMapper; }
private <T, O> Collection<O> internalMap( Collection<T> objects, Class<O> target, Collection<O> destination) { for (T t : objects) { destination.add(mapper.map(t, target)); } return destination; }
@Test public void testEventListeners() throws Exception { DozerBeanMapper eventMapper = context.getBean("mapperWithEventListener", DozerBeanMapper.class); assertNotNull(eventMapper.getEventListeners()); assertEquals(1, eventMapper.getEventListeners().size()); DozerEventListener eventListener = eventMapper.getEventListeners().get(0); assertEquals(EventTestListener.class, eventListener.getClass()); EventTestListener listener = context.getBean(EventTestListener.class); assertNotNull(listener); assertEquals(0, listener.getInvocationCount()); assertBasicMapping(eventMapper); assertEquals(4, listener.getInvocationCount()); }
/** 基于Dozer转换Collection中对象的类型. */ public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) { List<T> destinationList = Lists.newArrayList(); for (Object sourceObject : sourceList) { T destinationObject = dozer.map(sourceObject, destinationClass); destinationList.add(destinationObject); } return destinationList; }
@PostConstruct private void init() { mapper = new DozerBeanMapper(); mapper.addMapping( new BeanMappingBuilder() { @Override protected void configure() { mapping(CustomerDto.class, Customer.class).fields("properties", "properties"); } }); mapper.addMapping( new BeanMappingBuilder() { @Override protected void configure() { mapping(ContactDto.class, Contact.class).fields("communications", "communications"); } }); }
@Override public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException { // find the map id, so we can provide that when trying to map from source to destination String mapId = null; if (value != null) { Class<?> sourceType = value.getClass(); Class<?> destType = type; ClassMappingMetadata metadata = mapper.getMappingMetadata().getClassMapping(sourceType, destType); if (metadata != null) { mapId = metadata.getMapId(); } } // if the exchange is null, we have no chance to ensure that the TCCL is the one from the // CamelContext if (exchange == null) { return mapper.map(value, type, mapId); } T answer = null; ClassLoader prev = Thread.currentThread().getContextClassLoader(); ClassLoader contextCl = exchange.getContext().getApplicationContextClassLoader(); if (contextCl != null) { // otherwise, we ensure that the TCCL is the correct one LOG.debug("Switching TCCL to: {}.", contextCl); try { Thread.currentThread().setContextClassLoader(contextCl); answer = mapper.map(value, type, mapId); } finally { LOG.debug("Restored TCCL to: {}.", prev); Thread.currentThread().setContextClassLoader(prev); } } else { // just try with the current TCCL as-is answer = mapper.map(value, type, mapId); } return answer; }
public UpdateResponse update(String alias, ShowToSave showToSave) { DBObject show = findShow(alias); if (!show.get("alias").toString().equals(showToSave.getAlias())) { updateDenormalizedFields(show.get("alias").toString(), showToSave.getAlias()); } mapper.map(showToSave, show); db.getCollection("show").update(aliasOrId(alias), show); return new UpdateResponse(true); }
@Override public List<PermissionDto> findAll() { List<PermissionEntity> entities = permissionRepo.findAll(new Sort(Sort.Direction.ASC, "id")); List<PermissionDto> dtos = new ArrayList<PermissionDto>(); for (PermissionEntity e : entities) { dtos.add(mapper.map(e, PermissionDto.class)); } return dtos; }
public OkResponse contact(String alias, MailToShow mailToSend) { ValidationResult validate = captchaValidator.validate(mailToSend.getCaptcha()); if (!validate.isSuccess()) { throw new IllegalArgumentException("Rosszul megadott Captcha: " + validate.toString()); } MimeMessage mail = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mail, false); String body = "----- Ez a levél a tilos.hu műsoroldaláról lett küldve-----\n" + "\n" + "A form kitöltője a " + mailToSend.getFrom() + " email-t adta meg válasz címnek, de ennek valódiságát nem ellenőriztük." + "\n" + "-------------------------------------" + "\n" + mailToSend.getBody(); helper.setFrom("*****@*****.**"); helper.setReplyTo(mailToSend.getFrom()); helper.setSubject("[tilos.hu] " + mailToSend.getSubject()); helper.setText(body); DBObject one = db.getCollection("show").findOne(aliasOrId(alias)); if (one == null) { throw new IllegalArgumentException("No such show: " + alias); } ShowDetailed detailed = mapper.map(one, ShowDetailed.class); detailed .getContributors() .forEach( contributor -> { DBObject dbAuthor = db.getCollection("author").findOne(aliasOrId(contributor.getAuthor().getId())); if (dbAuthor.get("email") != null) { try { helper.setTo((String) dbAuthor.get("email")); } catch (MessagingException e) { throw new RuntimeException(e); } mailSender.send(mail); } }); } catch (Exception e) { throw new InternalErrorException("Can't send the email message: " + e.getMessage(), e); } return new OkResponse("Üzenet elküldve."); }
@Before public void setup() { try { vo = new WCartDetails(); vo.setId(1234567L); vo.setTransId(12345678L); vo.setItemNumber("12345678"); vo.setItemName("Auction items"); vo.setQuantity(10L); vo.setTotalAmount(100L); vo.setItemAmount(10L); vo.setShipping(10L); vo.setHandling(5L); vo.setInsurance(10L); vo.setExtraShipping(2L); vo.setFlags(8L); vo.setCurrencyCode("USD"); vo.setOptionName1("Option name1"); vo.setOptionName2("Option name2"); vo.setOptionSelection1("Option selection1"); vo.setOptionSelection2("Option selection2"); vo.setTotalHandling(8L); vo.setAccountNumber(BigInteger.ONE); vo.setCharset("utf-8"); vo.setTransDataMapId(123456789L); vo.setHostedButtonId(123456L); vo.setCost(120L); vo.setItemOptions("Item options"); vo.setItemDescription("Auction item description"); vo.setItemDiscount(1L); vo.setHostedButtonKeysText("HostedBtn"); vo.setReturnPolicyIdentifier("12345"); vo.setItemUpc("00012345678"); vo.setQuantityUnit(10L); vo.setIncentiveCode("55555"); vo.setIncentiveType(8L); vo.setTaxAmount(8L); vo.setTaxRate(8L); vo.setMpn("MPN"); vo.setIsbn("ISBN"); vo.setPlu("PLU"); vo.setModelNumber("12345"); vo.setStyleNumber("6789"); model = mapper.map(vo, WcartDetails2P2.class); } catch (Exception e) { fail(e.getMessage()); } }
public void initDozer() { mapper = new DozerBeanMapper(); List<String> myMappingFilesList = new ArrayList<String>(); for (String mf : this.myMappingFiles) { myMappingFilesList.add(mf); } if (myMappingFilesList.isEmpty()) { // test if "dozerBeanMapping.xml" exists in classpath InputStream is = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("dozerBeanMapping.xml"); if (is != null) myMappingFilesList.add("dozerBeanMapping.xml"); // default dozer mapping file (if exists) } ((DozerBeanMapper) mapper).setMappingFiles(myMappingFilesList); }
public List<ShowSimple> list(String status) { BasicDBObject criteria = new BasicDBObject(); // FIXME if (!"all".equals(status)) { criteria.put("status", ShowStatus.ACTIVE.ordinal()); } DBCursor selectedShows = db.getCollection("show").find(criteria).sort(new BasicDBObject("name", 1)); List<ShowSimple> mappedShows = new ArrayList<>(); for (DBObject show : selectedShows) { mappedShows.add(mapper.map(show, ShowSimple.class)); } Collections.sort( mappedShows, new Comparator<ShowSimple>() { @Override public int compare(ShowSimple s1, ShowSimple s2) { return s1.getName().toLowerCase().compareTo(s2.getName().toLowerCase()); } }); return mappedShows; }
@Bean public Mapper dozer() { DozerBeanMapper dozer = new DozerBeanMapper(); dozer.addMapping(new DozerCustomConfig()); return dozer; }
public <T> void map(Object source, T target) { mapper.map(source, target); }
public <T> T map(Object source, Class<T> target) { return mapper.map(source, target); }
/* * HuyNDN created on Feb 26, 2016 */ @Override public void save(PermissionDto permissionDto) { PermissionEntity entity = mapper.map(permissionDto, PermissionEntity.class); /* * Validate */ // These 2 lines of code is to avoid the exception: // org.hibernate.TransientPropertyValueException: object references an unsaved transient // instance - // save the transient instance before flushing : // vn.com.splussoftware.sms.model.entity.auth.PermissionEntity.user // -> vn.com.splussoftware.sms.model.entity.auth.SMSUserEntity (or SMSGroupEntity). if (entity.getGroup().getId() == null) { entity.setGroup(null); } else { // Check if this group exists if (!groupRepository.exists(permissionDto.getGroupId())) { throw new EntityNotFoundException( applicationContext.getMessage( GroupServiceImpl.class.getName() + MessagePropertiesConstant.KEY_ENTITY_NOT_FOUND, new Object[] {permissionDto.getGroupId()}, null)); } } if (entity.getUser().getId() == null) { entity.setUser(null); } else { // Check if this user exists if (!userRepository.exists(permissionDto.getUserId())) { throw new EntityNotFoundException( applicationContext.getMessage( UserServiceImpl.class.getName() + MessagePropertiesConstant.KEY_ENTITY_NOT_FOUND, new Object[] {permissionDto.getGroupId()}, null)); } } // Check if there's any same permission exists. List<PermissionEntity> ePermissions = permissionRepo.findByUserIdAndGroupIdAndTargetTypeAndTargetIdAndPermission( permissionDto.getUserId(), permissionDto.getGroupId(), permissionDto.getTargetType(), permissionDto.getTargetId(), permissionDto.getPermission()); if (ePermissions != null && !ePermissions.isEmpty()) { throw new EntityExistsException( applicationContext.getMessage( this.getClass().getName() + MessagePropertiesConstant.KEY_PERMISSION_ALREADY_EXISTS, // Get message from // message/messages.properties new Object[] {ePermissions.get(0).getId()}, applicationContext.getMessage( MessagePropertiesConstant.KEY_DEFAULT, null, null), // Get default message from message/messages.properties // in case the required message would be not found. null)); } permissionRepo.saveAndFlush(entity); }
/** 基于Dozer将对象A的值拷贝到对象B中. */ public static void copy(Object source, Object destinationObject) { dozer.map(source, destinationObject); }
public static <T> T map(Object source, Class<T> destinationClass, String mapId) { return mapper.map(source, destinationClass, mapId); }
public static void map(Object source, Object destination) { mapper.map(source, destination); }
public static <T> T map(Object object, Class<T> destinationClass) { return mapper.map(object, destinationClass); }
@PreDestroy private void destroy() { mapper.destroy(); }
@Bean public Mapper dozerBeanMapper() { DozerBeanMapper dozerBeanMapper = new DozerBeanMapper(); dozerBeanMapper.addMapping( new BeanMappingBuilder() { protected void configure() { mapping(FacebookProfile.class, com.techlooper.entity.FacebookProfile.class) .fields( "locale", "locale", FieldsMappingOptions.customConverter(LocaleConverter.class)); mapping( TwitterProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) .fields("name", "firstName", FieldsMappingOptions.copyByReference()) .fields("screenName", "userName", FieldsMappingOptions.copyByReference()); mapping( GitHubUserProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) .fields("name", "firstName", FieldsMappingOptions.copyByReference()) .fields("email", "emailAddress", FieldsMappingOptions.copyByReference()); mapping( Person.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) .fields("givenName", "firstName", FieldsMappingOptions.copyByReference()) .fields("familyName", "lastName", FieldsMappingOptions.copyByReference()) .fields("accountEmail", "emailAddress", FieldsMappingOptions.copyByReference()) .fields("imageUrl", "profileImageUrl", FieldsMappingOptions.copyByReference()); mapping( com.techlooper.entity.FacebookProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) .fields("email", "emailAddress", FieldsMappingOptions.copyByReference()); mapping( LinkedInProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) .fields( "profilePictureUrl", "profileImageUrl", FieldsMappingOptions.copyByReference()); mapping(UserEntity.class, UserInfo.class, TypeMappingOptions.oneWay()) .fields( "profiles", "profileNames", FieldsMappingOptions.customConverter(ProfileNameConverter.class)); mapping(UserInfo.class, UserEntity.class, TypeMappingOptions.oneWay()) .fields( "profileNames", "profiles", FieldsMappingOptions.customConverter(ProfileNameConverter.class)); mapping(UserEntity.class, VnwUserProfile.class).exclude("accessGrant"); mapping(SalaryReviewEntity.class, VNWJobSearchRequest.class) .fields("jobLevelIds", "jobLevel") .fields( "jobCategories", "jobCategories", FieldsMappingOptions.customConverter(ListCSVStringConverter.class)) .fields("netSalary", "jobSalary") .fields("locationId", "jobLocation"); mapping(VnwJobAlert.class, VnwJobAlertRequest.class) .fields( "jobLocations", "locationId", FieldsMappingOptions.customConverter(ListCSVStringConverter.class)) .fields("minSalary", "netSalary"); mapping(WebinarInfoDto.class, WebinarEntity.class, TypeMappingOptions.oneWay()) .exclude("createdDateTime"); mapping(ScrapeJobEntity.class, VNWJobSearchResponseDataItem.class) .fields("jobTitle", "title") .fields("jobTitleUrl", "url") .fields("companyLogoUrl", "logoUrl") .fields("createdDateTime", "postedOn"); mapping(ScrapeJobEntity.class, JobResponse.class) .fields("jobTitle", "title") .fields("jobTitleUrl", "url") .fields("createdDateTime", "postedOn") .fields("companyLogoUrl", "logoUrl"); mapping(ChallengeEntity.class, ChallengeDto.class) .fields("startDateTime", "startDate") .fields("submissionDateTime", "submissionDate") .fields("registrationDateTime", "registrationDate") .fields("ideaSubmissionDateTime", "ideaSubmissionDate") .fields("uxSubmissionDateTime", "uxSubmissionDate") .fields("prototypeSubmissionDateTime", "prototypeSubmissionDate"); } }); return dozerBeanMapper; }
public CreateResponse create(ShowToSave objectToSave) { DBObject newObject = mapper.map(objectToSave, BasicDBObject.class); newObject.put("alias", objectToSave.getAlias()); db.getCollection("show").insert(newObject); return new CreateResponse(((ObjectId) newObject.get("_id")).toHexString()); }
@Test public void testCreationByFactory() { DozerBeanMapper mapper = context.getBean("byFactory", DozerBeanMapper.class); assertTrue(mapper.getMappingFiles().isEmpty()); }
/** 基于Dozer转换对象的类型. */ public static <T> T map(Object source, Class<T> destinationClass) { return dozer.map(source, destinationClass); }