@PUT @Path("update/{id}") @Consumes("application/x-www-form-urlencoded") @Produces(MediaType.APPLICATION_XML) public Response updateGroup( @PathParam("id") int groupId, @FormParam("groupName") String groupName) throws SQLException { Session session = null; Group mappedGroup = new Group(); try { session = HibernateUtil.getSessionFactory().openSession(); Group group = session.load(Group.class, groupId); session.beginTransaction(); group.setGroupName(groupName); session.getTransaction().commit(); Mapper mapper = new DozerBeanMapper(); mappedGroup = mapper.map(group, Group.class); } catch (Exception e) { System.err.println("updateGroup failed, " + e.getMessage()); return Response.serverError().build(); } finally { if (session != null && session.isOpen()) { session.close(); } } return Response.ok(mappedGroup).build(); }
/** * Tests the feature request #88. * * <p>The mapper is configured so that an exception occurs while mapping the field "one" in the * setter method. Another exception occurs while mapping the field "two" in the custom converter. * The third field is mapped without an exception. */ @Test public void testCollectErrors() throws Exception { Mapper mapper = getMapper("collectErrors.xml"); // Create the test object TestObject to = newInstance(TestObject.class); to.setOne("throw me"); to.setTwo(2); to.setThree(InsideTestObject.createMethod()); try { mapper.map(to, TestObjectPrime.class); fail("CompositeMappingException was expected."); } catch (CompositeMappingException e) { // Check if the exceptions are gathered correctly assertNotNull(e.getCollectedErrors()); assertEquals(2, e.getCollectedErrors().size()); // Assert that the custom converter exception was not collected as InvocationTargetException for (Throwable throwable : e.getCollectedErrors()) { assertFalse(InvocationTargetException.class.equals(throwable.getClass())); } // Check if the result is partially filled despite the two exceptions assertTrue(e.getResult() instanceof TestObjectPrime); TestObjectPrime result = (TestObjectPrime) e.getResult(); assertNull(result.getThrowAllowedExceptionOnMapPrime()); assertNull(result.getTwoPrime()); assertNotNull(result.getThreePrime()); } }
public Facility updateFacilityCode(int id, String code) { TypedQuery<FacilityEntity> query = em.createQuery( "SELECT entity FROM FacilityEntity entity WHERE entity.id = :id", FacilityEntity.class); query.setParameter("id", id); List<FacilityEntity> entities = query.getResultList(); switch (entities.size()) { case 0: return null; case 1: { em.getTransaction().begin(); FacilityEntity entity = entities.get(0); if (code == null || code.length() == 0) { // do nothing } else { entity.code = code; } em.merge(entity); em.getTransaction().commit(); Mapper mapper = new DozerBeanMapper(); Facility destObject = mapper.map(entity, Facility.class); return destObject; } default: return null; } }
/** * 返回实现IModule接口的列表 * * @param applicationId * @return */ @Override public List<ModuleBean> getModuleByApplication(String applicationId) { Subject subject = shiroService.getSubject(); List<IModule> moduleList = ModuleManager.getInstall().getModuleList(applicationId); List<ModuleBean> moduleBeanList = new ArrayList<ModuleBean>(); if (moduleList == null) moduleList = new ArrayList<IModule>(); Mapper mapper = new DozerBeanMapper(); // 找出所有对应权限的功能模块 if (moduleList != null && !moduleList.isEmpty()) { for (IModule module : moduleList) { // 调用isPermitted不能传入空字符,故此默认值为KALIX_NOT_PERMISSION String modulePermission = StringUtils.isEmpty(module.getPermission()) ? Const.KALIX_NO_PERMISSION : module.getPermission(); // 具有权限或不进行权限验证,都通过 if (subject.hasRole(modulePermission) || modulePermission.equals(Const.KALIX_NO_PERMISSION)) { ModuleBean moduleBean = mapper.map(module, ModuleBean.class); moduleBean.setText(module.getText()); moduleBeanList.add(moduleBean); } } } if (moduleBeanList != null && !moduleBeanList.isEmpty()) { for (ModuleBean moduleBean : moduleBeanList) { moduleBean.setChildren(new ArrayList<MenuBean>()); List<IMenu> menuList = new ArrayList<IMenu>(); List<IMenu> allMenu = MenuManager.getInstall().getMenuList(moduleBean.getId()); // 去掉没有权限的菜单 if (allMenu != null && !allMenu.isEmpty()) { for (IMenu menu : allMenu) { // 调用hasRole不能传入空字符,故此默认值为KALIX_NOT_PERMISSION String menuPermission = StringUtils.isEmpty(menu.getPermission()) ? Const.KALIX_NO_PERMISSION : menu.getPermission(); // 具有权限或不进行权限验证,都通过 if (subject.hasRole(menuPermission) || menuPermission.equals(Const.KALIX_NO_PERMISSION)) { menuList.add(menu); } } } List<IMenu> rootMenus = getRootMenus(menuList); if (rootMenus != null && !rootMenus.isEmpty()) { for (IMenu rootMenu : rootMenus) { MenuBean menuBean = null; if (rootMenu != null) { menuBean = mapper.map(rootMenu, MenuBean.class); menuBean.setText(rootMenu.getText()); getMenuChildren(menuBean, menuList, mapper); } moduleBean.getChildren().add(menuBean); } } } } return moduleBeanList; }
private OrderDto mapOrder(Order o) { OrderDto orderDto = beanMapper.map(o, OrderDto.class); orderDto.onlyItem = beanMapper.map( o.getItems().get(0), OrderItemDto.class); // TODO: temporary solution only - remove later return orderDto; }
public static <S extends Object, T extends Object> Collection<T> map( Collection<S> sourceCollection, Class<T> targetClass) { Mapper mapper = createMapper(); Collection<T> targetCollection = new ArrayList<T>(); for (S item : sourceCollection) { targetCollection.add(mapper.map(item, targetClass)); } return targetCollection; }
public static void main(String[] args) { Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); GetOperatingInstructions operatingInstructions = new GetOperatingInstructions(); try { mapper.map(getOperatingInstructionsData(), operatingInstructions); } catch (Exception e) { System.out.println(e); } System.out.println(operatingInstructions); }
/** * 返回实现IMenu接口的列表 * * @param moduleId * @return */ @Override public MenuBean getMenuByModule(String moduleId) { List<IMenu> menuList = MenuManager.getInstall().getMenuList(moduleId); IMenu rootMenu = getRootMenu(menuList); /*List<String> mapFile=new ArrayList<>(); mapFile.add("META-INF/MenuMapper.xml");*/ Mapper mapper = new DozerBeanMapper(); MenuBean menuBean = null; if (rootMenu != null) { menuBean = mapper.map(rootMenu, MenuBean.class); menuBean.setText(rootMenu.getText()); getMenuChildren(menuBean, menuList, mapper); } return menuBean; }
@RequestMapping(method = RequestMethod.POST, consumes = "application/json; charset=utf-8") @PreAuthorize(value = "hasRole('AK_ADMIN')") @ResponseStatus(HttpStatus.CREATED) public void collectionAdd( @Valid @RequestBody UserResource p, HttpServletRequest request, HttpServletResponse response) { User bo = dozerBeanMapper.map(p, User.class); bo.setIdUser(null); try { userRepo.save(bo); } catch (DataAccessException e) { logger.error("Can't create user into DB", e); throw new DefaultSportManagerException( new ErrorResource( "db error", "Can't create user into DB", HttpStatus.INTERNAL_SERVER_ERROR)); } response.setHeader( "Location", request .getRequestURL() .append((request.getRequestURL().toString().endsWith("/") ? "" : "/")) .append(bo.getIdUser()) .toString()); }
@Path("/") @GET @Produces(MediaType.APPLICATION_JSON) public QuestionResponseDto getQuestion() { return dozerMapper.map( questionManager.loadQuestions().getRandomQuestion(), QuestionResponseDto.class); }
@Test public void testStringToEnum() throws Exception { Bean1 bean1 = new Bean1(); bean1.setSampleEnum(SampleEnum.TEST1.name()); Bean2 bean2 = dozer.map(bean1, Bean2.class); assertEquals(bean2.getSampleEnum(), SampleEnum.TEST1); }
/** * List all entities * * @return list containing all entities */ public static List<FMStatusRequestFactoryEntity> findAllFMStatuses() { List<FMStatusRequestFactoryEntity> returnList = new ArrayList<>(); for (FMStatus status : FMStatus.findAllFMStatuses()) returnList.add(mapper.map(status, FMStatusRequestFactoryEntity.class)); return returnList; }
public List<Facility> getAllFacilities(int offset, int limit) { TypedQuery<FacilityEntity> query = em.createQuery("SELECT entity FROM FacilityEntity entity", FacilityEntity.class); query.setFirstResult(offset); query.setMaxResults(limit); List<FacilityEntity> entities = query.getResultList(); List<Facility> result = new ArrayList<>(); Mapper mapper = new DozerBeanMapper(); for (FacilityEntity entity : entities) { Facility destObject = mapper.map(entity, Facility.class); result.add(destObject); } return result; }
@Test public void testEnumToString() throws Exception { Bean2 bean2 = new Bean2(); bean2.setSampleEnum(SampleEnum.TEST2); Bean1 bean1 = dozer.map(bean2, Bean1.class); assertEquals(SampleEnum.TEST2.name(), bean1.getSampleEnum()); }
@GET public Response getPostazioni() { logger.debug("getPostazioni called!"); // Execute query. // PostazioneService ps = ServiceFactory.createPostazioneService(); QueryResult<Postazione> result = ps.listPostazioni(null, null, null, null, null); // Set up response. // Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); PostazioniDTO dto = mapper.map(result, PostazioniDTO.class); return Response.ok().entity(dto).build(); }
@Override public <T> List<T> mapTo(Collection<?> objects, Class<T> mapToClass) { List<T> mappedCollection = new ArrayList<>(); for (Object object : objects) { mappedCollection.add(dozer.map(object, mapToClass)); } return mappedCollection; }
@Override public <T1, T2> List<T2> convertList(List<T1> liste1, Class<T2> destC) { java.util.ArrayList<T2> liste2 = new java.util.ArrayList<T2>(); for (T1 o1 : liste1) { liste2.add(mapper.map(o1, destC)); } return liste2; }
@Override public <T1, T2> Collection<T2> convertCollection(Collection<T1> col1, Class<T2> destC) { java.util.ArrayList<T2> col2 = new java.util.ArrayList<T2>(); for (T1 o1 : col1) { col2.add(mapper.map(o1, destC)); } return col2; }
@Override public SystemBean getSystem() { Subject subject = shiroService.getSubject(); SystemBean systemBean = new SystemBean(); if (subject == null) return systemBean; Mapper mapper = new DozerBeanMapper(); HeaderBean headerBean = mapper.map(systemService.getHeader(), HeaderBean.class); systemBean.setHeaderBean(headerBean); FooterBean footerBean = mapper.map(systemService.getFooter(), FooterBean.class); systemBean.setFooterBean(footerBean); BodyBean bodyBean = new BodyBean(); bodyBean.setApplicationBeanList( DozerHelper.map(mapper, systemService.getBody().getApplications(), ApplicationBean.class)); systemBean.setBodyBean(bodyBean); return systemBean; }
@Override public OfferListWebServiceVO getOfferListWebMethod() { initEJB(); List<OfferVO> offerVOs = offerService.findAll(); OfferListWebServiceVO rv = new OfferListWebServiceVO(); rv.setList(new ArrayList<OfferWebServiceVO>()); for (OfferVO offerVO : offerVOs) { rv.getList().add(mapper.map(offerVO, OfferWebServiceVO.class)); } return rv; }
@Test public void convert() { beanMapper.map("METHOD", ElementType.class); EasyMock.expectLastCall().andReturn(ElementType.METHOD); EasyMock.replay(beanMapper); Assert.assertEquals( ElementType.METHOD, converter.convert("METHOD", null, TypeDescriptor.valueOf(ElementType.class))); EasyMock.verify(beanMapper); }
public Facility getFacilityWithId(int id) { TypedQuery<FacilityEntity> query = em.createQuery( "SELECT entity FROM FacilityEntity entity WHERE entity.id = :id", FacilityEntity.class); query.setParameter("id", id); List<FacilityEntity> entities = query.getResultList(); switch (entities.size()) { case 0: return null; case 1: { Mapper mapper = new DozerBeanMapper(); FacilityEntity entity = entities.get(0); Facility destObject = mapper.map(entity, Facility.class); return destObject; } default: return null; } }
@RequestMapping( value = "/backoffice/orders/activeGroupedByArticle.json", method = RequestMethod.GET) public @ResponseBody List<ArticleWithOrdersDto> getActiveOrdersGroupedByArticle() { LinkedHashMap<Long, ArticleWithOrders> articlesWithOrders = menuService.getActiveOrdersByArticle(); List<ArticleWithOrdersDto> articlesWithOrdersDtos = new ArrayList<ArticleWithOrdersDto>(); for (ArticleWithOrders articleWithOrders : articlesWithOrders.values()) { ArticleWithOrdersDto articleWithOrdersDto = new ArticleWithOrdersDto(); articleWithOrdersDto.entity = beanMapper.map(articleWithOrders.entity, ArticleDto.class); for (Order order : articleWithOrders.items.values()) articleWithOrdersDto.items.add(beanMapper.map(order, OrderDto.class)); articlesWithOrdersDtos.add(articleWithOrdersDto); } return articlesWithOrdersDtos; }
@GET @Path("/{id}") @Produces(MediaType.APPLICATION_XML) public Response getGroup(@PathParam("id") int groupId) throws SQLException { Session session = null; Group mappedGroup = null; try { session = HibernateUtil.getSessionFactory().openSession(); Group group = session.load(Group.class, groupId); Mapper mapper = new DozerBeanMapper(); mappedGroup = mapper.map(group, Group.class); } catch (Exception e) { System.err.println("getGroup failed, " + e.getMessage()); return Response.serverError().build(); } finally { if (session != null && session.isOpen()) { session.close(); } } return Response.ok(mappedGroup).build(); }
@Test public final void testRoundtripMapping() { try { if (inputElement == null) { unmarshalInput(); } Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance(); com.wwidesigner.note.Tuning domainTuning = mapper.map(inputElement, com.wwidesigner.note.Tuning.class); Tuning bindTuning = mapper.map(domainTuning, Tuning.class); outputFile = new File(writePath + "mapperTest.xml"); outputFile.delete(); bindFactory.marshalToXml(bindTuning, outputFile); XmlDiff diff = new XmlDiff(inputFile, outputFile); DetailedDiff detailedDiff = new DetailedDiff(diff); assertTrue(detailedDiff.toString(), detailedDiff.identical()); } catch (Exception e) { fail(e.getMessage()); } }
@RequestMapping(value = "auth", method = RequestMethod.GET) ResponseEntity<PageDto> isAuth(@AuthenticationPrincipal BeadsanUserDetails userDetail) { PageDto pageDto = new PageDto(); if (userDetail != null) { UserInfo userInfo = userDetail.getUserInfo(); HeaderDto headerDto = mapper.map(userInfo, HeaderDto.class); headerDto.setAuth(true); LoginDto loginDto = mapper.map(userInfo, LoginDto.class); pageDto.setHeaderDto(headerDto); pageDto.setLoginDto(loginDto); return new ResponseEntity<>(pageDto, null, HttpStatus.OK); } else { HeaderDto headerDto = new HeaderDto(); headerDto.setAuth(false); pageDto.setHeaderDto(headerDto); return new ResponseEntity<>(pageDto, null, HttpStatus.UNAUTHORIZED); } }
@RequestMapping( value = "/backoffice/orders/activeGroupedByDeliveryLocation.json", method = RequestMethod.GET) public @ResponseBody List<DeliveryLocationWithArticlesDto> getActiveOrdersGroupedByDeliveryLocation() { LinkedHashMap<Long, DeliveryLocationWithArticles> locationsWithArticles = menuService.getActiveOrdersByDeliveryLocation(); List<DeliveryLocationWithArticlesDto> locationsWithArticlesDtos = new ArrayList<DeliveryLocationWithArticlesDto>(); for (DeliveryLocationWithArticles deliveryLocationWithArticles : locationsWithArticles.values()) { DeliveryLocation deliveryLocation = deliveryLocationWithArticles.entity; DeliveryLocationWithArticlesDto deliveryLocationWithArticlesDto = new DeliveryLocationWithArticlesDto(); deliveryLocationWithArticlesDto.entity = beanMapper.map(deliveryLocation, DeliveryLocationDto.class); deliveryLocationWithArticlesDto.countOrderItems = deliveryLocationWithArticles.countOrderItems; for (ArticleWithOrders articleWithOrders : deliveryLocationWithArticles.items.values()) { Article article = articleWithOrders.entity; // Construct complete DTO object before it is added to parent group DTO ArticleWithOrdersDto articleWithOrdersDto = new ArticleWithOrdersDto(); articleWithOrdersDto.entity = beanMapper.map(article, ArticleDto.class); for (Order order : articleWithOrders.items.values()) { OrderDto orderDto = beanMapper.map(order, OrderDto.class); articleWithOrdersDto.items.add(orderDto); } deliveryLocationWithArticlesDto.items.add(articleWithOrdersDto); } locationsWithArticlesDtos.add(deliveryLocationWithArticlesDto); } return locationsWithArticlesDtos; }
@RequestMapping("newOrderForm") public String newOrderForm(OrderForm orderForm, Model model) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Account account = userDetails.getAccount(); Order order = new Order(); order.initOrder(account, cart); beanMapper.map(order, orderForm); model.addAttribute(order); return "order/NewOrderForm"; }
/** * 递归函数加载子菜单 * * @param menuBean * @param menuList */ private void getMenuChildren(MenuBean menuBean, List<IMenu> menuList, Mapper mapper) { if (menuList == null || menuList.isEmpty()) return; List<MenuBean> childMenuList = new ArrayList<>(); for (IMenu menu : menuList) { if (menu.getParentMenuId() != null && menu.getParentMenuId().equals(menuBean.getId())) { MenuBean mBean = mapper.map(menu, MenuBean.class); mBean.setText(menu.getText()); childMenuList.add(mBean); getMenuChildren(mBean, menuList, mapper); } } menuBean.setChildren(childMenuList); }
@Path("/{username}") @GET @Produces(MediaType.APPLICATION_JSON) public AllQuestionResponseDto getAllQuestions(@PathParam("username") String username) { List<Game> games = gameUserDataManager.getGamesByResultType(username, ResponseType.NEED_RESPONSE); AllQuestionResponseDto results = new AllQuestionResponseDto(); for (Game game : games) { results.addQuestion( dozerMapper.map( questionManager.loadQuestions().getQuestionById(game.getId()), QuestionResponseDto.class)); } return results; }