Java 类org.apache.commons.collections.IteratorUtils 实例源码

项目:obevo    文件:CsvReaderDataSource.java   
/**
 * Putting this init here so that we can discover the file fields before running the actual rec
 */
public void init() {
    if (!this.initialized) {
        try {
            MutableList<String> fields;
            if (csvVersion == CsvStaticDataReader.CSV_V2) {
                CSVFormat csvFormat = getCsvFormat(delim, nullToken);
                this.csvreaderV2 = new CSVParser(reader, csvFormat);
                this.iteratorV2 = csvreaderV2.iterator();
                fields = ListAdapter.adapt(IteratorUtils.toList(iteratorV2.next().iterator()));
            } else {
                this.csvreaderV1 = new au.com.bytecode.opencsv.CSVReader(this.reader, this.delim);
                fields = ArrayAdapter.adapt(this.csvreaderV1.readNext());
            }

            this.fields = fields.collect(this.convertDbObjectName);
        } catch (Exception e) {
            throw new DeployerRuntimeException(e);
        }
        this.initialized = true;
    }
}
项目:athena    文件:YangXmlUtilsTest.java   
/**
 * Tests getting a single object configuration via passing the path and the map of the desired values.
 *
 * @throws ConfigurationException if the testing xml file is not there.
 */
@Test
public void testGetXmlConfigurationFromMap() throws ConfigurationException {
    Map<String, String> pathAndValues = new HashMap<>();
    pathAndValues.put("capable-switch.id", "openvswitch");
    pathAndValues.put("switch.id", "ofc-bridge");
    pathAndValues.put("controller.id", "tcp:1.1.1.1:1");
    pathAndValues.put("controller.ip-address", "1.1.1.1");
    XMLConfiguration cfg = utils.getXmlConfiguration(OF_CONFIG_XML_PATH, pathAndValues);
    testCreateConfig.load(getClass().getResourceAsStream("/testCreateSingleYangConfig.xml"));
    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);

    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));

    assertEquals("Wrong string configuaration", utils.getString(testCreateConfig),
                 utils.getString(cfg));
}
项目:athena    文件:YangXmlUtilsTest.java   
/**
 * Tests getting a multiple object nested configuration via passing the path
 * and a list of YangElements containing with the element and desired value.
 *
 * @throws ConfigurationException
 */
@Test
public void getXmlConfigurationFromYangElements() throws ConfigurationException {

    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);
    testCreateConfig.load(getClass().getResourceAsStream("/testYangConfig.xml"));
    List<YangElement> elements = new ArrayList<>();
    elements.add(new YangElement("capable-switch", ImmutableMap.of("id", "openvswitch")));
    elements.add(new YangElement("switch", ImmutableMap.of("id", "ofc-bridge")));
    List<ControllerInfo> controllers =
            ImmutableList.of(new ControllerInfo(IpAddress.valueOf("1.1.1.1"), 1, "tcp"),
                             new ControllerInfo(IpAddress.valueOf("2.2.2.2"), 2, "tcp"));
    controllers.stream().forEach(cInfo -> {
        elements.add(new YangElement("controller", ImmutableMap.of("id", cInfo.target(),
                                                                   "ip-address", cInfo.ip().toString())));
    });
    XMLConfiguration cfg =
            new XMLConfiguration(YangXmlUtils.getInstance()
                                         .getXmlConfiguration(OF_CONFIG_XML_PATH, elements));
    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));
    assertEquals("Wrong string configuaration", utils.getString(testCreateConfig),
                 utils.getString(cfg));
}
项目:dremio-oss    文件:QueryProfileParser.java   
@SuppressWarnings("unchecked")
private void parsePhysicalPlan() throws IOException {
  if (queryProfile.getJsonPlan() == null || queryProfile.getJsonPlan().isEmpty()) {
    return;
  }
  // Parse the plan and map tables to major fragment and operator ids.
  final Map<String, Object> plan = mapper.readValue(queryProfile.getJsonPlan(), Map.class);
  for (Map.Entry<String, Object> entry: plan.entrySet()) {
    checkIsAssignable(entry.getKey(), entry.getValue().getClass(), Map.class);
    final Map<String, Object> operatorInfo = (Map)entry.getValue();
    final String operator = (String) operatorInfo.get("\"op\"");
    if (operator != null && operator.contains("Scan") && operatorInfo.containsKey("\"values\"")) {
      // Get table name
      checkIsAssignable(entry.getKey() + ": values", operatorInfo.get("\"values\"").getClass(), Map.class);
      final Map<String, Object> values = (Map)operatorInfo.get("\"values\"");
      if (values.containsKey("\"table\"")) {
        // TODO (Amit H) remove this after we clean up code.
        final String tokens = ((String) values.get("\"table\"")).replaceAll("^\\[|\\]$", "");
        final String tablePath = PathUtils.constructFullPath(IteratorUtils.toList(splitter.split(tokens).iterator()));
        operatorToTable.put(entry.getKey(), tablePath);
      }
    }
  }
}
项目:jpa-unit    文件:SqlScriptTest.java   
@SuppressWarnings("unchecked")
@Test
public void testRemovalOfCommentsProperSplittingOfStatementsAndTrimmingOfEachOfIt() {
    // GIVEN
    final SqlScript script = new SqlScript(TEST_SCRIPT);

    // WHEN
    final List<String> list = IteratorUtils.toList(script.iterator());

    // THEN
    assertThat(list.size(), equalTo(12));
    assertThat(list, everyItem(not(containsString("comment"))));
    assertThat(list, everyItem(not(startsWith(" "))));
    assertThat(list, everyItem(not(startsWith("\t"))));
    assertThat(list, everyItem(not(endsWith(" "))));
    assertThat(list, everyItem(not(endsWith("\t"))));
}
项目:OpenCyclos    文件:SimpleCollectionBinder.java   
@Override
public String readAsString(final Object object) {
    final StringBuilder sb = new StringBuilder();
    sb.append('[');
    final Converter<T> converter = resolveConverter();
    for (final Iterator<?> it = IteratorUtils.getIterator(object); it.hasNext();) {
        final Object value = it.next();
        final T baseValue = CoercionHelper.coerce(elementType, value);
        sb.append('"').append(converter.toString(baseValue)).append('"');
        if (it.hasNext()) {
            sb.append(',');
        }
    }
    sb.append(']');
    return sb.toString();
}
项目:OpenCyclos    文件:MapBinder.java   
@Override
public void writeAsString(final Object object, final Object value) {
    validateNestedBinders();
    final Map<String, String> values = new HashMap<String, String>();
    if (value instanceof Map<?, ?>) {
        for (final Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            final String keyAsString = keyBinder.readAsString(Collections.singletonMap(keyBinder.getPath(), entry.getKey()));
            final String valueAsString = valueBinder.readAsString(Collections.singletonMap(valueBinder.getPath(), entry.getValue()));
            values.put(keyAsString, valueAsString);
        }
    } else {
        for (final Iterator<?> it = IteratorUtils.getIterator(value); it.hasNext();) {
            final Object current = it.next();
            values.put(keyBinder.readAsString(current), valueBinder.readAsString(current));
        }
    }
    doWrite(object, values);
}
项目:OpenCyclos    文件:CoercionHelper.java   
/**
    * Converts an object to a collection of the given type, using the given element type
    * @return The resulting collection - it may be empty, but never null
    */
   @SuppressWarnings({ "unchecked", "rawtypes" })
   public static <T> Collection<T> coerceCollection(final Class<T> elementType, final Class<? extends Collection> collectionType, final Object value) {
final ArrayList<T> al = new ArrayList<T>();
       //final Collection<T> collection = ClassHelper.instantiate(collectionType == null ? al.getClass() : collectionType);
Collection<T> collection;
if(collectionType == null) {
    collection = ClassHelper.instantiate(al.getClass());
} else {
    collection = ClassHelper.instantiate(collectionType);
}

       final Iterator<?> iterator = IteratorUtils.getIterator(value);
       while (iterator.hasNext()) {
           collection.add(coerce(elementType, iterator.next()));
       }
       return collection;
   }
项目:OpenCyclos    文件:ExportMembersTransactionsReportToCsvAction.java   
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected List<?> executeQuery(final ActionContext context) {
    final MembersReportHandler reportHandler = getReportHandler();
    final Pair<MembersTransactionsReportDTO, Iterator<MemberTransactionSummaryReportData>> pair = reportHandler.handleTransactionsSummary(context);
    final MembersTransactionsReportDTO dto = pair.getFirst();
    final Iterator<MemberTransactionSummaryReportData> reportIterator = pair.getSecond();
    final Iterator iterator = IteratorUtils.filteredIterator(reportIterator, new Predicate() {
        @Override
        public boolean evaluate(final Object element) {
            final MemberTransactionSummaryReportData data = (MemberTransactionSummaryReportData) element;
            if (dto.isIncludeNoTraders()) {
                return true;
            }
            return data.isHasData();
        }
    });
    return new IteratorListImpl(iterator);
}
项目:OpenCyclos    文件:ExportMembersTransactionsDetailsToCsvAction.java   
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected List<?> executeQuery(final ActionContext context) {
    final MembersReportHandler reportHandler = getReportHandler();
    final Pair<MembersTransactionsReportDTO, Iterator<MemberTransactionDetailsReportData>> pair = reportHandler.handleTransactionsDetails(context);
    final MembersTransactionsReportDTO dto = pair.getFirst();
    final Iterator<MemberTransactionDetailsReportData> reportIterator = pair.getSecond();
    final Iterator iterator = IteratorUtils.filteredIterator(reportIterator, new Predicate() {
        @Override
        public boolean evaluate(final Object element) {
            final MemberTransactionDetailsReportData data = (MemberTransactionDetailsReportData) element;
            if (dto.isIncludeNoTraders()) {
                return true;
            }
            return data.getAmount() != null;
        }
    });
    return new IteratorListImpl(iterator);
}
项目:dasein-cloud-azurepack    文件:AzurePackNetworkSupport.java   
@Override
public void removeSubnet(final String providerSubnetId) throws CloudException, InternalException {
    List<DataCenter> dataCenters = new ArrayList(IteratorUtils.toList(this.provider.getDataCenterServices().listDataCenters(this.provider.getContext().getRegionId()).iterator()));
    String dataCenterId = dataCenters.get(0).getProviderDataCenterId();

    WAPSubnetsModel subnetsModel = new AzurePackRequester(provider, new AzurePackNetworkRequests(provider).listSubnets(dataCenterId).build()).withJsonProcessor(WAPSubnetsModel.class).execute();

    WAPSubnetModel foundSubnetModel = (WAPSubnetModel)CollectionUtils.find(subnetsModel.getSubnets(), new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            return ((WAPSubnetModel) object).getId().equalsIgnoreCase(providerSubnetId);
        }
    });

    if(foundSubnetModel == null)
        throw new InternalException("Invalid subnet providerSubnetId provided");

    new AzurePackRequester(provider, new AzurePackNetworkRequests(provider).deleteSubnet(foundSubnetModel).build()).execute();
}
项目:dasein-cloud-azurepack    文件:AzurePackVirtualMachineSupportTest.java   
@Test
public void listAllProductsShouldReturnCorrectHardwareProfileProducts() throws CloudException, InternalException {
    new ListProductsRequestExecutorMockUp();
    List<VirtualMachineProduct> products = IteratorUtils
            .toList(azurePackVirtualMachineSupport.listAllProducts().iterator());

    //listAllProducts returns all available hardware profile plus default product
    assertEquals("listProducts doesn't return correct result", 2, products.size());
    VirtualMachineProduct virtualMachineProduct = products.get(0);
    assertEquals("listProducts doesn't return correct result", HWP_1_NAME, virtualMachineProduct.getName());
    assertEquals("listProducts doesn't return correct result", HWP_1_ID, virtualMachineProduct.getProviderProductId());
    assertEquals("listProducts doesn't return correct result", Integer.parseInt(HWP_1_CPU_COUNT), virtualMachineProduct.getCpuCount());
    assertEquals("listProducts doesn't return correct result", Double.parseDouble(HWP_1_MEMORY), virtualMachineProduct.getRamSize().getQuantity());
    assertEquals("listProducts doesn't return correct result", Storage.MEGABYTE,
            virtualMachineProduct.getRamSize().getUnitOfMeasure());

    //assert default product
    virtualMachineProduct = products.get(1);
    assertEquals("listProducts doesn't return correct result", "default", virtualMachineProduct.getName().toLowerCase());
    assertEquals("listProducts doesn't return correct result", "default", virtualMachineProduct.getProviderProductId().toLowerCase());
    assertEquals("listProducts doesn't return correct result", "default", virtualMachineProduct.getDescription().toLowerCase());

}
项目:dasein-cloud-azurepack    文件:AzurePackImageSupportTest.java   
@Test
public void searchImagesShouldReturnCorrectResult() throws CloudException, InternalException {
    new GetAllImagesRequestExecutorMockUp();
    List<MachineImage> images;
    images = IteratorUtils.toList(azurePackImageSupport.searchImages(null, null, null, null).iterator());
    assertEquals("searchImages doesn't return correct result", 6, images.size());

    images = IteratorUtils.toList(azurePackImageSupport.searchImages(ACCOUNT_NO, null, null, null).iterator());
    assertEquals("searchImages doesn't return correct result", 2, images.size());

    images = IteratorUtils.toList(azurePackImageSupport.searchImages(ACCOUNT_NO, null, Platform.WINDOWS, null).iterator());
    assertEquals("searchImages doesn't return correct result", 2, images.size());

    images = IteratorUtils.toList(azurePackImageSupport.searchImages(ACCOUNT_NO, null, Platform.WINDOWS, null,
            ImageClass.MACHINE).iterator());
    assertEquals("searchImages doesn't return correct result", 2, images.size());

    images = IteratorUtils.toList(azurePackImageSupport.searchImages(ACCOUNT_NO, null, Platform.WINDOWS, null,
            ImageClass.KERNEL).iterator());
    assertEquals("searchImages doesn't return correct result", 0, images.size());
}
项目:event-direct-mts    文件:StringIndexGraphWrapper.java   
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Graph {\n");
    Iterator<Integer> it = base.iterator();
    while (it.hasNext()) {
        Integer node = it.next();
        sb.append("\t" + get(node) + ": ");
        @SuppressWarnings("unchecked")
        List<String> neighbors = IndexUtil.map(IteratorUtils.toList(base.getNeighbors(node)), this);
        sb.append(StringUtils.join(neighbors, ','));
        sb.append("\n");
    }
    sb.append("}\n");
    return sb.toString();
}
项目:enhanced-snapshots    文件:VolumeServiceImpl.java   
private Set<VolumeDto> convert(Iterable<BackupEntry> entries) {
    List<BackupEntry> backupList = IteratorUtils.toList(entries.iterator());
    Comparator<BackupEntry> cmp = Comparator.comparingLong(backup-> Long.parseLong(backup.getTimeCreated()));
    Collections.sort(backupList, cmp.reversed());
    Map<String, VolumeDto> dtos = new HashMap<>();

    for (BackupEntry entry : backupList) {
        VolumeDto dto = new VolumeDto();

        dto.setVolumeId(entry.getVolumeId());
        dto.setSize(0);

        dto.setInstanceID(EMPTY);
        dto.setVolumeName(entry.getVolumeName());
        dto.setTags(Collections.EMPTY_LIST);
        dto.setAvailabilityZone(EMPTY);
        dto.setSnapshotId(EMPTY);
        dto.setState(REMOVED_VOLUME_STATE);
        if(!dtos.containsKey(dto.getVolumeId())) {
            dtos.put(dto.getVolumeId(), dto);
        }
    }
    return new HashSet<>(dtos.values());
}
项目:omr    文件:ParticipationHelper.java   
/**
 * Cria as participações por pessoa, atribuindo a cada pessoa uma variante do exame contida na coleção examVariants
 * 
 * @param eventVO
 * @param pessoas
 * @param examVariants
 */
private void registrarParticipacoes(EventVO eventVO, Collection<PessoaVO> pessoas, List<ExamVariantVO> examVariants) {

    boolean criticarDuplicidade = false;

    //looping iterator, para distribuição das variações de exame
    Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

    for (PessoaVO pessoaVO : pessoas) {
        ExamVariantVO nowExamVariant = itExVar.next();

        if(pessoaExameNaoRegistrado(eventVO, pessoaVO, nowExamVariant)){

            ParticipationVO participationVO = new ParticipationVO();
            participationVO.setPessoaVO(pessoaVO);
            participationVO.setExamVariantVO(nowExamVariant);
            eventVO.getParticipations().add(participationVO);
        }
    }

}
项目:omr    文件:OMRModelTest.java   
private void registrarParticipacoes(Set<EventVO> eventos, Set<PessoaVO> pessoas, Set<ExamVariantVO> examVariants) {

        Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

        for (EventVO eventVO : eventos) {
            for (PessoaVO pessoaVO : pessoas) {
                ParticipationVO participationVO = new ParticipationVO();

                participationVO.setPessoaVO(pessoaVO);

                ExamVariantVO nowExamVariant = itExVar.next();
                participationVO.setExamVariantVO(nowExamVariant);

                eventVO.getParticipations().add(participationVO);
            }
        }
    }
项目:omr    文件:ParticipationHelper.java   
/**
 * Cria as participações por pessoa, atribuindo a cada pessoa uma variante do exame contida na coleção examVariants
 * 
 * @param eventVO
 * @param pessoas
 * @param examVariants
 */
private void registrarParticipacoes(EventVO eventVO, Collection<PessoaVO> pessoas, List<ExamVariantVO> examVariants) {

    boolean criticarDuplicidade = false;

    //looping iterator, para distribuição das variações de exame
    Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

    for (PessoaVO pessoaVO : pessoas) {
        ExamVariantVO nowExamVariant = itExVar.next();

        if(pessoaExameNaoRegistrado(eventVO, pessoaVO, nowExamVariant)){

            ParticipationVO participationVO = new ParticipationVO();
            participationVO.setPessoaVO(pessoaVO);
            participationVO.setExamVariantVO(nowExamVariant);
            eventVO.getParticipations().add(participationVO);
        }
    }

}
项目:omr    文件:OMRModelTest.java   
private void registrarParticipacoes(Set<EventVO> eventos, Set<PessoaVO> pessoas, Set<ExamVariantVO> examVariants) {

        Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

        for (EventVO eventVO : eventos) {
            for (PessoaVO pessoaVO : pessoas) {
                ParticipationVO participationVO = new ParticipationVO();

                participationVO.setPessoaVO(pessoaVO);

                ExamVariantVO nowExamVariant = itExVar.next();
                participationVO.setExamVariantVO(nowExamVariant);

                eventVO.getParticipations().add(participationVO);
            }
        }
    }
项目:omr    文件:ParticipationHelper.java   
/**
 * Cria as participações por pessoa, atribuindo a cada pessoa uma variante do exame contida na coleção examVariants
 * 
 * @param eventVO
 * @param pessoas
 * @param examVariants
 */
private void registrarParticipacoes(EventVO eventVO, Collection<PessoaVO> pessoas, List<ExamVariantVO> examVariants) {

    boolean criticarDuplicidade = false;

    //looping iterator, para distribuição das variações de exame
    Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

    for (PessoaVO pessoaVO : pessoas) {
        ExamVariantVO nowExamVariant = itExVar.next();

        if(pessoaExameNaoRegistrado(eventVO, pessoaVO, nowExamVariant)){

            ParticipationVO participationVO = new ParticipationVO();
            participationVO.setPessoaVO(pessoaVO);
            participationVO.setExamVariantVO(nowExamVariant);
            eventVO.getParticipations().add(participationVO);
        }
    }

}
项目:omr    文件:OMRModelTest.java   
private void registrarParticipacoes(Set<EventVO> eventos, Set<PessoaVO> pessoas, Set<ExamVariantVO> examVariants) {

        Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

        for (EventVO eventVO : eventos) {
            for (PessoaVO pessoaVO : pessoas) {
                ParticipationVO participationVO = new ParticipationVO();

                participationVO.setPessoaVO(pessoaVO);

                ExamVariantVO nowExamVariant = itExVar.next();
                participationVO.setExamVariantVO(nowExamVariant);

                eventVO.getParticipations().add(participationVO);
            }
        }
    }
项目:omr    文件:OMRModelTest.java   
private void registrarParticipacoes(Set<EventVO> eventos, Set<PessoaVO> pessoas, Set<ExamVariantVO> examVariants) {

        Iterator<ExamVariantVO> itExVar = IteratorUtils.loopingIterator(examVariants);

        for (EventVO eventVO : eventos) {
            for (PessoaVO pessoaVO : pessoas) {
                ParticipationVO participationVO = new ParticipationVO();

                participationVO.setPessoaVO(pessoaVO);

                ExamVariantVO nowExamVariant = itExVar.next();
                participationVO.setExamVariantVO(nowExamVariant);

                eventVO.getParticipations().add(participationVO);
            }
        }
    }
项目:mybus    文件:ServiceReportMongoDAO.java   
private Iterable<ServiceReport> getServiceReports(String status, Date date) throws ParseException {
    Date startDate = ServiceConstants.df.parse(systemProperties.getStringProperty("service.startDate", "2017-06-01"));
    if(date != null) {
        startDate = date;
    }
    Criteria criteria = new Criteria();
    if(status == null){
        criteria.andOperator(Criteria.where("status").exists(false),
                Criteria.where("journeyDate").gte(startDate));
    } else {
        criteria.andOperator(Criteria.where("status").is(status),
                Criteria.where("journeyDate").gte(startDate));
    }
    Query query = new Query(criteria);
    query.with(new Sort(Sort.Direction.DESC,"journeyDate"));
    query.fields().exclude("bookings");
    query.fields().exclude("expenses");
    query.fields().exclude("serviceExpense");
    List<ServiceReport> reports = IteratorUtils.toList(mongoTemplate.find(query, ServiceReport.class).iterator());
    return reports;
}
项目:mybus    文件:SchedulerService.java   
@Scheduled(cron = "0 0 5 * * *")
//@Scheduled(fixedDelay = 50000)
public void checkExpiryDates () {
    logger.info("checking expiry date..." + systemProperties.getProperty(SystemProperties.SysProps.EXPIRATION_BUFFER));
    int buffer = Integer.parseInt(systemProperties.getProperty(SystemProperties.SysProps.EXPIRATION_BUFFER));
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) - buffer));
    List<Vehicle> vehicles = IteratorUtils.toList(vehicleMongoDAO.findExpiring(calendar.getTime()).iterator());
    if (!vehicles.isEmpty()) {
        Map<String, Object> context = new HashMap<>();
        context.put("permitExpiring", vehicles.stream().filter(v -> v.getPermitExpiry().isBefore(calendar.getTime().getTime())).collect(Collectors.toList()));
        context.put("fitnessExpiring", vehicles.stream().filter(v -> v.getFitnessExpiry().isBefore(calendar.getTime().getTime())).collect(Collectors.toList()));
        context.put("authExpiring", vehicles.stream().filter(v -> v.getAuthExpiry().isBefore(calendar.getTime().getTime())).collect(Collectors.toList()));
        context.put("pollutionExpiring", vehicles.stream().filter(v -> v.getPollutionExpiry().isBefore(calendar.getTime().getTime())).collect(Collectors.toList()));
        context.put("insuranceExpiring", vehicles.stream().filter(v -> v.getInsuranceExpiry().isBefore(calendar.getTime().getTime())).collect(Collectors.toList()));
        String content = velocityEngineService.trasnform(context, VelocityEngineService.EXPIRING_DOCUMENTS_TEMPLATE);
        logger.info("Sending email for notifying expiring documents ...");
        emailSender.sendExpiringNotifications(content);
    }
}
项目:onos    文件:YangXmlUtilsTest.java   
/**
 * Tests getting a single object configuration via passing the path and the map of the desired values.
 *
 * @throws ConfigurationException if the testing xml file is not there.
 */
@Test
public void testGetXmlConfigurationFromMap() throws ConfigurationException {
    Map<String, String> pathAndValues = new HashMap<>();
    pathAndValues.put("capable-switch.id", "openvswitch");
    pathAndValues.put("switch.id", "ofc-bridge");
    pathAndValues.put("controller.id", "tcp:1.1.1.1:1");
    pathAndValues.put("controller.ip-address", "1.1.1.1");
    XMLConfiguration cfg = utils.getXmlConfiguration(OF_CONFIG_XML_PATH, pathAndValues);
    testCreateConfig.load(getClass().getResourceAsStream("/testCreateSingleYangConfig.xml"));
    assertNotEquals("Null testConfiguration", new XMLConfiguration(), testCreateConfig);

    assertEquals("Wrong configuaration", IteratorUtils.toList(testCreateConfig.getKeys()),
                 IteratorUtils.toList(cfg.getKeys()));

    assertEquals("Wrong string configuaration", utils.getString(testCreateConfig),
                 utils.getString(cfg));
}
项目:mybus    文件:BookingManager.java   
/**
 * validates all the bookings for an agent. This is triggered when agent is allotted to an office.
 * This will update the bookings made by that agent and service reports containing the bookings.
 * @param agent
 */
public void validateAgentBookings(Agent agent) {
    if(agent.getBranchOfficeId() == null) {
        return;
    }
    Iterable<Booking> bookings = bookingDAO.findByBookedByAndHasValidAgent(agent.getUsername(), false);
    Set<String> serviceNumbers = new HashSet<>();
    for(Booking booking: bookings) {
        serviceNumbers.add(booking.getServiceId());
        booking.setHasValidAgent(true);
        bookingDAO.save(booking);
    }
    for(String serviceId: serviceNumbers) {
        List<Booking> invalidBookings = IteratorUtils.toList(
                bookingDAO.findByIdAndHasValidAgent(serviceId, false).iterator());
        if(invalidBookings.size() == 0) {
            ServiceReport serviceReport = serviceReportDAO.findOne(serviceId);
            if(serviceReport.isInvalid()) {
                serviceReport.setInvalid(false);
                serviceReportDAO.save(serviceReport);
            }
        }
    }
}
项目:mybus    文件:ServiceReportsManager.java   
public ServiceForm getForm(String id) {
    ServiceForm serviceForm = serviceFormDAO.findOne(id);
    Iterable<Booking> bookings = bookingDAO.findByFormId(serviceForm.getId());
    /*
    //load the service expense
    serviceForm.setServiceExpense(serviceExpenseManager.getServiceExpenseByServiceReportId(serviceForm.getServiceReportId()));
    */
    //round up the digits
    serviceForm.setNetRedbusIncome(roundUp(serviceForm.getNetRedbusIncome()));
    serviceForm.setNetOnlineIncome(roundUp(serviceForm.getNetOnlineIncome()));
    serviceForm.setNetCashIncome(roundUp(serviceForm.getNetCashIncome()));
    serviceForm.setNetIncome(roundUp(serviceForm.getNetIncome()));
    serviceForm.setExpenses(IteratorUtils.toList(paymentDAO.findByFormId(id).iterator()));
    serviceForm.setBookings(IteratorUtils.toList(bookings.iterator()));
    if(serviceForm.getSubmittedBy() != null) {
        serviceForm.getAttributes().put("submittedBy", userManager.getUser(serviceForm.getSubmittedBy()).getFullName());
    } else {
        serviceForm.getAttributes().put("submittedBy", userManager.getUser(serviceForm.getCreatedBy()).getFullName());
    }
    return serviceForm;
}
项目:mybus    文件:LayoutManager.java   
/**
 * Module to build a map of <layoutId, layoutName>,
 * @param allLayouts -- when true all the names will be returned, when false only active layout names are returned
 * @return
 */
public Map<String, String> getLayoutNames(boolean allLayouts) {
    List<Layout> layouts = null;
    if(allLayouts) {
        layouts = IteratorUtils.toList(layoutDAO.findAll().iterator());
    } else {
        //find only active cities
        layouts = IteratorUtils.toList(layoutDAO.findByActive(true).iterator());
    }
    if (layouts == null || layouts.isEmpty() ) {
        return new HashMap<>();
    }
    Map<String, String> map = layouts.stream().collect(
            Collectors.toMap(Layout::getId, layout -> layout.getName()));
    return map;
}
项目:mybus    文件:RoleControllerTest.java   
@Test
public void testUpdateRole() throws Exception {
    JSONObject role = new JSONObject();
    role.put("name", "test");
    ResultActions actions = mockMvc.perform(asUser(post("/api/v1/createRole")
            .content(getObjectMapper().writeValueAsBytes(role))
            .contentType(MediaType.APPLICATION_JSON), currentUser));
            actions.andExpect(status().isOk());
    role.put("name", "test1");
    mockMvc.perform(asUser(put(format("/api/v1/role/%s", role.get("id")))
            .content(getObjectMapper().writeValueAsBytes(role))
            .contentType(MediaType.APPLICATION_JSON), currentUser));
    List<Role> roles = IteratorUtils.toList(roleDAO.findAll().iterator());
    Assert.assertEquals(1,roles.size());
    Assert.assertEquals("test1", role.get("name"));
}
项目:mybus    文件:RoleControllerTest.java   
@Test
public void testDeleteRole() throws Exception {
    Role role = new Role("test");
    Role role1 = new Role("test1");
    roleDAO.save(role);
    roleDAO.save(role1);
    Assert.assertEquals(true, roleDAO.findAll().iterator().hasNext());
    List<Role> roles = IteratorUtils.toList(roleDAO.findAll().iterator());
    Assert.assertEquals(2, roles.size());
    ResultActions actions = mockMvc.perform(asUser(delete(format("/api/v1/role/%s", role.getId())) ,currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$.deleted").value(true));
    Assert.assertEquals(true, roleDAO.findAll().iterator().hasNext());
    roles = IteratorUtils.toList(roleDAO.findAll().iterator());
    Assert.assertEquals(1, roles.size());
}
项目:mybus    文件:RoleControllerTest.java   
@Test
public void testUpdatemanagingRole() throws Exception {
    JSONObject role = new JSONObject();
    role.put("name", "test");
    ResultActions actions = mockMvc.perform(asUser(post("/api/v1/createRole")
            .content(getObjectMapper().writeValueAsBytes(role))
            .contentType(MediaType.APPLICATION_JSON), currentUser));
            actions.andExpect(status().isOk());
    role.put("name", "test1");
    String menus = "['home','Menu','Partner']";
    role.put("menus", menus);
    mockMvc.perform(asUser(put(format("/api/v1/manageingrole/%s", role.get("id")))
            .content(getObjectMapper().writeValueAsBytes(role))
            .contentType(MediaType.APPLICATION_JSON), currentUser));
    List<Role> roles = IteratorUtils.toList(roleDAO.findAll().iterator());
    Assert.assertEquals(1,roles.size());
    Assert.assertEquals("test1", role.get("name"));
}
项目:mybus    文件:RouteControllerTest.java   
@Test
public void testCreateRoute() throws Exception {
    City fromCity = new City("FromCity"+new ObjectId().toString(), "state", true, new ArrayList<>());
    City toCity = new City("ToCity"+new ObjectId().toString(), "state", true, new ArrayList<>());

    cityManager.saveCity(fromCity);
    cityManager.saveCity(toCity);
    Route route = new Route("TestRoute"+new ObjectId().toString(), fromCity.getId(),
            toCity.getId(), new LinkedHashSet<>(), true);
    ResultActions actions = mockMvc.perform(asUser(post("/api/v1/route").content(getObjectMapper()
            .writeValueAsBytes(route)).contentType(MediaType.APPLICATION_JSON), currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$.name").value(route.getName()));
    actions.andExpect(jsonPath("$.fromCityId").value(route.getFromCityId()));
    actions.andExpect(jsonPath("$.toCityId").value(route.getToCityId()));
    List<Route> routeList = IteratorUtils.toList(routeDAO.findAll().iterator());
    Assert.assertEquals(1, routeList.size());
}
项目:mybus    文件:PlanTypeControllerTest.java   
@Test
public void testGetAll() throws Exception {
    for(int i=0;i<3;i++) {
        PlanType planType = new PlanType();
        planType.setName("PlanType"+i);
        planType.setBalance(200.0);
        planType.setType("planType");
        planType.setCommissionType("0");
        planType.setSettlementFrequency("1");
        planTypeDAO.save(planType);
    }
    List<PlanType> plans = IteratorUtils.toList(planTypeDAO.findAll().iterator());
    Assert.assertEquals(3, plans.size());
    ResultActions actions = mockMvc.perform(asUser(get("/api/v1/plans"), currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$").isArray());
    actions.andExpect(jsonPath("$", Matchers.hasSize(3)));
}
项目:mybus    文件:PlanTypeControllerTest.java   
@Test
public void testCreate() throws Exception {
    JSONObject plan = new JSONObject();
    plan.put("name", "Pname");
    plan.put("balance", 200.00);
    plan.put("type", "123");
    plan.put("commissionType", "0");
    plan.put("settlementFrequency", true);
    ResultActions actions = mockMvc.perform(asUser(post("/api/v1/plan")
            .content(getObjectMapper().writeValueAsBytes(plan))
            .contentType(MediaType.APPLICATION_JSON), currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$.name").value(plan.get("name").toString()));
    actions.andExpect(jsonPath("$.balance").value(Double.parseDouble(plan.get("balance").toString())));
    actions.andExpect(jsonPath("$.type").value(plan.get("type").toString()));
    actions.andExpect(jsonPath("$.commissionType").value(plan.get("commissionType").toString()));
    actions.andExpect(jsonPath("$.settlementFrequency").value(plan.get("settlementFrequency").toString()));
    List<PlanType> plans = IteratorUtils.toList(planTypeDAO.findAll().iterator());
    Assert.assertEquals(1, plans.size());
}
项目:mybus    文件:ShipmentControllerTest.java   
@Test
public void testCreateShipment() throws Exception {
    BranchOffice fromBranch = new BranchOffice("FromBranch", "1234");
    BranchOffice toBranch = new BranchOffice("ToBranch", "1234");
    fromBranch = branchOfficeManager.save(fromBranch);
    toBranch = branchOfficeManager.save(toBranch);
    Shipment shipment = ShipmentTestService.createNew();
    shipment.setFromBranchId(fromBranch.getId());
    shipment.setToBranchId(toBranch.getId());
    shipment.setShipmentType(ShipmentType.FREE);


    ResultActions actions = mockMvc.perform(asUser(post("/api/v1/shipment").content(getObjectMapper()
            .writeValueAsBytes(shipment)).contentType(MediaType.APPLICATION_JSON), currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$.fromBranchId").value(shipment.getFromBranchId()));
    actions.andExpect(jsonPath("$.toBranchId").value(shipment.getToBranchId()));
    List<Shipment> shipments = IteratorUtils.toList(shipmentDAO.findAll().iterator());
    assertEquals(1, shipments.size());
}
项目:mybus    文件:UserControllerTest.java   
@Test
public void testGetAll() throws Exception {

        User user = new User();
        UserType userType;
        user.setUserName("xxx");
        user.setAddress1("address");
        user.setContact(23456785);

    List<User> users = IteratorUtils.toList(userDAO.findAll().iterator());
    Assert.assertEquals(1, users.size());
    ResultActions actions = mockMvc.perform(asUser(get("/api/v1/users"), currentUser));
    actions.andExpect(status().isOk());
    actions.andExpect(jsonPath("$").isArray());
    actions.andExpect(jsonPath("$", Matchers.hasSize(1)));
}
项目:mybus    文件:PaymentDAOTest.java   
@Test
public void testCreatePayments(){
    for(int i =0;i< 20;i++) {
        Payment payment = new Payment();
        payment.setName("Books Bill");
        if(i%3 == 0) {
            payment.setStatus("Approved");
        }
        payment.setAmount(2000);
        paymentDAO.save(payment);
    }

    List<Payment> payments = IteratorUtils.toList(paymentDAO.findAll().iterator());
    Assert.assertEquals(20, payments.size());
    Page<Payment> page = paymentMongoDAO.findPendingPayments(null);
    Assert.assertEquals(13, page.getContent().size());



}
项目:mybus    文件:RouteManagerTest.java   
@Test
public void testSaveRouteWithNewName() {
    Route savedRoute = routeManager.saveRoute(routeTestService.createTestRoute());
    //try saving the route with same name
    savedRoute.setId(null);
    //change the name and it should be good
    savedRoute.setName(savedRoute.getName() + "_New");
    routeManager.saveRoute(savedRoute);
    List<Route> routes = IteratorUtils.toList(routeDAO.findAll().iterator());
    Assert.assertEquals(2, routes.size());
    List cities =IteratorUtils.toList(cityDAO.findAll().iterator());
    Assert.assertEquals(2, cities.size());
    List activeRoutes = IteratorUtils.toList(routeDAO.findByActive(true).iterator());
    Assert.assertEquals(2, activeRoutes.size());
    List inActiveRoutes = IteratorUtils.toList(routeDAO.findByActive(false).iterator());
    Assert.assertEquals(0, inActiveRoutes.size());
}
项目:geowave    文件:JobContextAdapterStore.java   
@Override
public CloseableIterator<DataAdapter<?>> getAdapters() {
    final CloseableIterator<DataAdapter<?>> it = persistentAdapterStore.getAdapters();
    // cache any results
    return new CloseableIteratorWrapper<DataAdapter<?>>(
            it,
            IteratorUtils.transformedIterator(
                    it,
                    new Transformer() {

                        @Override
                        public Object transform(
                                final Object obj ) {
                            if (obj instanceof DataAdapter) {
                                adapterCache.put(
                                        ((DataAdapter) obj).getAdapterId(),
                                        (DataAdapter) obj);
                            }
                            return obj;
                        }
                    }));
}