当前位置: 首页>>代码示例>>Java>>正文


Java SuperCsvException类代码示例

本文整理汇总了Java中org.supercsv.exception.SuperCsvException的典型用法代码示例。如果您正苦于以下问题:Java SuperCsvException类的具体用法?Java SuperCsvException怎么用?Java SuperCsvException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SuperCsvException类属于org.supercsv.exception包,在下文中一共展示了SuperCsvException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getFieldsByExplicitIndex

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private static Map<Integer, BeanCell> getFieldsByExplicitIndex(List<Field> fields, BeanDescriptor beanDescriptor, String context) {
    Map<Integer, BeanCell> result = new HashMap<>();
    for (Field field : fields) {
        CsvField fieldAnnotation = field.getAnnotation(CsvField.class);
        if (fieldAnnotation != null) {
            if (result.containsKey(fieldAnnotation.index())) {
                throw new SuperCsvException(Form.at("Explicit order-index {} was declared twice (Field: {}", fieldAnnotation.index(),
                        field.getName()));
            }

            CellProcessor cellProcessor = BeanCellProcessorExtractor.createCellProcessorFor(beanDescriptor, field, context);
            FieldAccessStrategy fieldAccessStrategy = createFieldAccessStrategy(beanDescriptor.getAccessType());
            result.put(fieldAnnotation.index(), new ExistingBeanCell(field, cellProcessor, fieldAccessStrategy));
        }
    }

    return result;
}
 
开发者ID:dmn1k,项目名称:super-csv-declarative,代码行数:19,代码来源:BeanCells.java

示例2: populateBean

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private <T> T populateBean(final T resultBean, List<Object> processedColumns, BeanCells cells) {
    for (int i = 0; i < processedColumns.size(); i++) {
        final Object fieldValue = processedColumns.get(i);

        BeanCell cell = cells.getCell(i);
        if (cell == null || cell.getType() == null) {
            continue;
        }

        // ClassUtils handles boxed types
        if (fieldValue != null && ClassUtils.isAssignable(fieldValue.getClass(), cell.getType(), true)) {
            cell.setValue(resultBean, fieldValue);
        } else {
            Class<?> fieldValueClass = fieldValue == null ? Object.class : fieldValue.getClass();
            TypeConverter<Object, Object> converter
                    = (TypeConverter<Object, Object>) typeConverterRegistry.getConverter(fieldValueClass, cell.getType());
            if (converter == null) {
                throw new SuperCsvException(Form.at("No converter registered from type {} to type {}. Add one or fix your CellProcessor-annotations to return the field's type",
                        fieldValueClass.getName(), cell.getType().getName()));
            }
            cell.setValue(resultBean, converter.convert(fieldValue));
        }
    }

    return resultBean;
}
 
开发者ID:dmn1k,项目名称:super-csv-declarative,代码行数:27,代码来源:CsvDeclarativeBeanReader.java

示例3: readIntoBean

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private <T> T readIntoBean(final T bean, BeanDescriptor beanDescriptor, BeanCells cells)
        throws IOException {

    if (readRow()) {
        if (CsvMappingModeType.STRICT.equals(beanDescriptor.getMappingMode()) && cells.getCorrectlyMappedFieldCount() != length()) {
            throw new SuperCsvException(Form.at("MappingMode.STRICT: Number of mapped bean-fields ({}] and csv-cells ({}) does not match.", cells.getCorrectlyMappedFieldCount(), length()));
        }
        List<CellProcessor> rowProcessors = new ArrayList<>();
        for (int i = 0; i < length(); i++) {
            rowProcessors.add(cells.getCell(i).getProcessor());
        }

        List<Object> processedColumns = new ArrayList<>();
        executeProcessors(processedColumns, rowProcessors.toArray(new CellProcessor[rowProcessors.size()]));

        return populateBean(bean, processedColumns, cells);
    }

    return null; // EOF
}
 
开发者ID:dmn1k,项目名称:super-csv-declarative,代码行数:21,代码来源:CsvDeclarativeBeanReader.java

示例4: testQuotedFieldWithUnexpectedEOF

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Tests the readColumns() method when EOF is reached within quote scope.
 */
@Test
public void testQuotedFieldWithUnexpectedEOF() throws Exception {
	
	// EOF reached within quote scope
	final String input = "\"quoted spanning\ntwo lines with EOF reached before another quote";
	tokenizer = createTokenizer(input, NORMAL_PREFERENCE);
	try {
		tokenizer.readColumns(columns);
		fail("should have thrown SuperCsvException");
	}
	catch(SuperCsvException e) {
		assertEquals("unexpected end of file while reading quoted column beginning on line 1 and ending on line 2",
			e.getMessage());
	}
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:19,代码来源:TokenizerTest.java

示例5: testQuotedFieldWithUnexpectedNewline

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Tests the readColumns() method when a newline is reached in quote
 * scoped when a single line is only supposed to be read
 */
@Test
public void testQuotedFieldWithUnexpectedNewline() throws Exception {

	// Row 2 has a missing trailing quote
	final String input = "col1,col2\n" +
			"\"foo\",\"bar\n" +
			"\"baz\",\"zoo\"\n" +
			"\"aaa\",\"bbb\"";
	CsvPreference pref = new CsvPreference.Builder(NORMAL_PREFERENCE)
			.maxLinesPerRow(1).build();

	tokenizer = createTokenizer(input, pref);
	try {
		boolean first = tokenizer.readColumns(columns);
		assertEquals(true , first);

		tokenizer.readColumns(columns);
		fail("should have thrown SuperCsvException");
	}
	catch(SuperCsvException e) {
		assertEquals("unexpected end of line while reading quoted column on line 2",
				e.getMessage());
	}
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:29,代码来源:TokenizerTest.java

示例6: testIllegalGetHeader

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Tests the getCsvHeader(true) can't be called when a line has already been read.
 */
@Test
public void testIllegalGetHeader() throws IOException {
	
	abstractReader.getHeader(true);
	
	try {
		abstractReader.getHeader(true);
		fail("should have thrown SuperCsvException");
	}
	catch(SuperCsvException e) {
		assertEquals("CSV header must be fetched as the first read operation, but 1 lines have already been read",
			e.getMessage());
	}
	
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:19,代码来源:AbstractCsvReaderTest.java

示例7: testReadForBrokenCSV

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private void testReadForBrokenCSV(final CsvDozerBeanReader brokenCsvBeanReader, final List<SurveyResponse> responses,
		final String expectedMessage, final int expectedRowsRead) throws IOException {
	brokenCsvBeanReader.getHeader(true);
	brokenCsvBeanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING);
	Exception expected = null;
	for(int i = 0; i < 4; i++) {
		try{
			final SurveyResponse response = readSurveyResponse(brokenCsvBeanReader, USE_PROCESSORS, EXISTING_BEAN);
			if(response != null) {
				responses.add(response);
			}
		} catch (final SuperCsvException e) {
			expected = e;
		}
	}
	assertNotNull(expected);
	assertEquals(expectedMessage, expected.getLocalizedMessage());
	assertEquals(expectedRowsRead, responses.size());
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:20,代码来源:CsvDozerBeanReaderTest.java

示例8: convertDefault

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private List<CsvError> convertDefault(final SuperCsvException exception, final BeanMapping<?> beanMapping) {
    
    final CsvContext context = exception.getCsvContext();
    
    final Map<String, Object> variables = new HashMap<>();
    variables.put("lineNumber", context.getLineNumber());
    variables.put("rowNumber", context.getRowNumber());
    variables.put("columnNumber", context.getColumnNumber());
    
    final String defaultMessage = exception.getMessage();
    
    final String errorCode = "csvError";
    final String objectName = beanMapping.getType().getSimpleName();
    final String[] errorCodes = codeGenerator.generateCodes(errorCode, objectName);
    
    final CsvError error = new CsvError.Builder(objectName, errorCodes)
            .variables(variables)
            .defaultMessage(defaultMessage)
            .build();
    
    return Arrays.asList(error);
    
}
 
开发者ID:mygreen,项目名称:super-csv-annotation,代码行数:24,代码来源:CsvExceptionConverter.java

示例9: getFields

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
List<Field> getFields() {
    withCsvFieldAnnotation.clear();
    withoutCsvFieldAnnotation.clear();

    extractFields(beanDescriptor.getBeanType());

    if (withCsvFieldAnnotation.isEmpty()) {
        return new ArrayList(withoutCsvFieldAnnotation);
    }

    if (!withoutCsvFieldAnnotation.isEmpty()) {
        List<String> ignoredFieldNames = new ArrayList<>();
        for (Field withoutAnnotation : withoutCsvFieldAnnotation) {
            ignoredFieldNames.add(withoutAnnotation.getName());
        }

        if (CsvMappingModeType.STRICT.equals(beanDescriptor.getMappingMode())) {
            throw new SuperCsvException(Form.at("MappingMode.STRICT: You used @CsvField somewhere in the type hierarchy of {} but there are fields without it."
                    + " Those fields are unmapped: {}", beanDescriptor.getBeanType().getName(), String.join(", ", ignoredFieldNames)));
        }

        LOGGER.warn("You used @CsvField somewhere in the type hierarchy of {} but there are fields without it."
                + " Those fields will be ignored by SuperCSV: {}", beanDescriptor.getBeanType().getName(), String.join(", ", ignoredFieldNames));
    }

    return new ArrayList(withCsvFieldAnnotation);
}
 
开发者ID:dmn1k,项目名称:super-csv-declarative,代码行数:28,代码来源:FieldExtractor.java

示例10: readBeanWithIllegalExplicitFieldOrdering

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
@Test(expected = SuperCsvException.class)
public void readBeanWithIllegalExplicitFieldOrdering() throws IOException {
    setupBeanReader(SIMPLE_BEAN_SIMPLE_ANNOTATIONS_CSV);
    BeanWithIllegalExplicitFieldOrder john = new BeanWithIllegalExplicitFieldOrder(null, "Doe", 42, 100.5);
    BeanWithIllegalExplicitFieldOrder max = new BeanWithIllegalExplicitFieldOrder("Max", "Mus", 22, 21.4);

    assertEquals(john, beanReader.read(BeanWithIllegalExplicitFieldOrder.class));
    assertEquals(max, beanReader.read(BeanWithIllegalExplicitFieldOrder.class));
    assertNull(beanReader.read(BeanWithIllegalExplicitFieldOrder.class));
}
 
开发者ID:dmn1k,项目名称:super-csv-declarative,代码行数:11,代码来源:CsvDeclarativeBeanReaderTest.java

示例11: throwGpsLoaderExceptionWithContext

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
private void throwGpsLoaderExceptionWithContext(SuperCsvException e, CsvContext csvContext) {
    StringBuilder message = new StringBuilder();
    message.append("Could not load gps records from csv file because of a problem at line ");
    message.append(csvContext.getLineNumber());
    message.append(".");
    throw new GpsRecordLoadingException(message.toString(), e);
}
 
开发者ID:NLeSC,项目名称:eEcology-Classification,代码行数:8,代码来源:GpsRecordDtoCsvLoader.java

示例12: executeCellProcessors

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Processes each element in the source List (using the corresponding processor chain in the processors array) and
 * adds it to the destination List. A <tt>null</tt> CellProcessor in the array indicates that no processing is
 * required and the element should be added as-is.
 * 
 * @param destination
 *            the List to add the processed elements to (which is cleared before it's populated)
 * @param source
 *            the List of source elements to be processed
 * @param processors
 *            the array of CellProcessors used to process each element. The number of elements in this array must
 *            match the size of the source List. A <tt>null</tt> CellProcessor in this array indicates that no
 *            processing is required and the element should be added as-is.
 * @param lineNo
 *            the current line number
 * @param rowNo
 *            the current row number
 * @throws NullPointerException
 *             if destination, source or processors is null
 * @throws SuperCsvConstraintViolationException
 *             if a CellProcessor constraint failed
 * @throws SuperCsvException
 *             if source.size() != processors.length, or CellProcessor execution failed
 */
public static void executeCellProcessors(final List<Object> destination, final List<?> source,
	final CellProcessor[] processors, final int lineNo, final int rowNo) {
	
	if( destination == null ) {
		throw new NullPointerException("destination should not be null");
	} else if( source == null ) {
		throw new NullPointerException("source should not be null");
	} else if( processors == null ) {
		throw new NullPointerException("processors should not be null");
	}
	
	// the context used when cell processors report exceptions
	final CsvContext context = new CsvContext(lineNo, rowNo, 1);
	context.setRowSource(new ArrayList<Object>(source));
	
	if( source.size() != processors.length ) {
		throw new SuperCsvException(String.format(
			"The number of columns to be processed (%d) must match the number of CellProcessors (%d): check that the number"
				+ " of CellProcessors you have defined matches the expected number of columns being read/written",
			source.size(), processors.length), context);
	}
	
	destination.clear();
	
	for( int i = 0; i < source.size(); i++ ) {
		
		context.setColumnNumber(i + 1); // update context (columns start at 1)
		
		if( processors[i] == null ) {
			destination.add(source.get(i)); // no processing required
		} else {
			destination.add(processors[i].execute(source.get(i), context)); // execute the processor chain
		}
	}
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:60,代码来源:Util.java

示例13: filterListToMap

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Converts a List to a Map using the elements of the nameMapping array as the keys of the Map.
 * 
 * @param destinationMap
 *            the destination Map (which is cleared before it's populated)
 * @param nameMapping
 *            the keys of the Map (corresponding with the elements in the sourceList). Cannot contain duplicates.
 * @param sourceList
 *            the List to convert
 * @param <T>
 *            the type of the values in the map
 * @throws NullPointerException
 *             if destinationMap, nameMapping or sourceList are null
 * @throws SuperCsvException
 *             if nameMapping and sourceList are not the same size
 */
public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,
	final List<? extends T> sourceList) {
	if( destinationMap == null ) {
		throw new NullPointerException("destinationMap should not be null");
	} else if( nameMapping == null ) {
		throw new NullPointerException("nameMapping should not be null");
	} else if( sourceList == null ) {
		throw new NullPointerException("sourceList should not be null");
	} else if( nameMapping.length != sourceList.size() ) {
		throw new SuperCsvException(
			String
				.format(
					"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)",
					nameMapping.length, sourceList.size()));
	}
	
	destinationMap.clear();
	
	for( int i = 0; i < nameMapping.length; i++ ) {
		final String key = nameMapping[i];
		
		if( key == null ) {
			continue; // null's in the name mapping means skip column
		}
		
		// no duplicates allowed
		if( destinationMap.containsKey(key) ) {
			throw new SuperCsvException(String.format("duplicate nameMapping '%s' at index %d", key, i));
		}
		
		destinationMap.put(key, sourceList.get(i));
	}
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:50,代码来源:Util.java

示例14: getHeader

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
public String[] getHeader(final boolean firstLineCheck) throws IOException {
	
	if( firstLineCheck && tokenizer.getLineNumber() != 0 ) {
		throw new SuperCsvException(String.format(
			"CSV header must be fetched as the first read operation, but %d lines have already been read",
			tokenizer.getLineNumber()));
	}
	
	if( readRow() ) {
		return columns.toArray(new String[columns.size()]);
	}
	
	return null;
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:18,代码来源:AbstractCsvReader.java

示例15: testQuotedFieldWithTwoMaxLines

import org.supercsv.exception.SuperCsvException; //导入依赖的package包/类
/**
 * Tests the readColumns() method when a newline is reached in quote
 * scoped when two lines are only supposed to be read
 */
@Test
public void testQuotedFieldWithTwoMaxLines() throws Exception {

	// Row 2 has a missing trailing quote
	final String input = "col1,col2\n" +
			"\"foo\",\"bar\n" +
			"baz,zoo\n" +
			"aaa,bbb";
	CsvPreference pref = new CsvPreference.Builder(NORMAL_PREFERENCE)
			.maxLinesPerRow(2).build();

	tokenizer = createTokenizer(input, pref);
	try {
		boolean first = tokenizer.readColumns(columns);
		assertEquals(true , first);

		boolean second = tokenizer.readColumns(columns);
		assertEquals(true , second);

		tokenizer.readColumns(columns);
		fail("should have thrown SuperCsvException");
	}
	catch(SuperCsvException e) {
		assertEquals("max number of lines to read exceeded while reading quoted column beginning on line 2 and ending on line 3",
				e.getMessage());
	}
}
 
开发者ID:super-csv,项目名称:super-csv,代码行数:32,代码来源:TokenizerTest.java


注:本文中的org.supercsv.exception.SuperCsvException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。