org.supercsv.util.CsvContext Java Examples

The following examples show how to use org.supercsv.util.CsvContext. 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: AbstractJodaParsingProcessor.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null or is not a String
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	if (!(value instanceof String)) {
		throw new SuperCsvCellProcessorException(String.class, value,
				context, this);
	}

	final String string = (String) value;
	final T result;
	try {
		if (formatter != null) {
			result = parse(string, formatter);
		} else {
			result = parse(string);
		}
	} catch (IllegalArgumentException e) {
		throw new SuperCsvCellProcessorException("Failed to parse value",
				context, this, e);
	}

	return next.execute(result, context);
}
 
Example #2
Source File: ParseDouble.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null, isn't a Double or String, or can't be parsed as a Double
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	final Double result;
	if( value instanceof Double ) {
		result = (Double) value;
	} else if( value instanceof String ) {
		try {
			result = new Double((String) value);
		}
		catch(final NumberFormatException e) {
			throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value),
				context, this, e);
		}
	} else {
		final String actualClassName = value.getClass().getName();
		throw new SuperCsvCellProcessorException(String.format(
			"the input value should be of type Double or String but is of type %s", actualClassName), context, this);
	}
	
	return next.execute(result, context);
}
 
Example #3
Source File: WordForbid.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(final Object value, final CsvContext context) {
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String stringValue = value.toString();
    
    final List<String> hitWords = words.stream()
            .filter(word -> stringValue.contains(word))
            .collect(Collectors.toList());
    
    if(!hitWords.isEmpty()) {
        final String joinedWords = String.join(", ", hitWords);
        throw createValidationException(context)
            .messageFormat("'%s' contains the forbidden substring '%s'", stringValue, joinedWords)
            .rejectedValue(stringValue)
            .messageVariables("words", hitWords)
            .build();
    }
    
    return next.execute(value, context);
}
 
Example #4
Source File: AbstractCsvAnnotationBeanWriter.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * 行の例外情報をメッセージに変換したりします。
 * @param bindingErrors
 * @param context
 * @param rowException
 */
protected void processErrors(final CsvBindingErrors bindingErrors, final CsvContext context,
        final Optional<SuperCsvRowException> rowException) {
    
    if(bindingErrors.hasErrors()) {
        final List<String> message = bindingErrors.getAllErrors().stream()
                .map(error -> error.format(exceptionConverter.getMessageResolver(), exceptionConverter.getMessageInterpolator()))
                .collect(Collectors.toList());
        errorMessages.addAll(message);
        
        final SuperCsvBindingException bindingException = new SuperCsvBindingException("has binding error.", context, bindingErrors);
        rowException.ifPresent(re -> bindingException.addAllProcessingErrors(re.getColumnErrors()));
        
        throw bindingException;
        
    }
}
 
Example #5
Source File: ParseZoneId.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws SuperCsvCellProcessorException if value is null or is not a String
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	if( !(value instanceof String) ) {
		throw new SuperCsvCellProcessorException(String.class, value, context, this);
	}
	final ZoneId result;
	try {
		if( aliasMap != null ) {
			result = ZoneId.of((String) value, aliasMap);
		} else {
			result = ZoneId.of((String) value);
		}
	}
	catch(DateTimeException e) {
		throw new SuperCsvCellProcessorException("Failed to parse value as a ZoneId", context, this, e);
	}
	return next.execute(result, context);

}
 
Example #6
Source File: LengthMin.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             {@literal if value is null}
 * @throws SuperCsvConstraintViolationException
 *             {@literal if length is < min or length > max}
 */
@SuppressWarnings("unchecked")
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String stringValue = value.toString();
    final int length = stringValue.length();
    if( length < min ) {
        throw createValidationException(context)
            .messageFormat("the length (%d) of value '%s' does not lie the min (%d) values (inclusive)",
                    length, stringValue, min)
            .rejectedValue(stringValue)
            .messageVariables("min", getMin())
            .messageVariables("length", length)
            .build();
            
    }
    
    return next.execute(stringValue, context);
}
 
Example #7
Source File: Pattern.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final boolean matches = pattern.matcher((String) value).matches();
    if(!matches) {
        throw createValidationException(context)
            .messageFormat("'%s' does not match the regular expression '%s'", value, getRegex())
            .rejectedValue(value)
            .messageVariables("regex", getRegex())
            .messageVariables("flags", getFlags())
            .messageVariables("description", getDescription())
            .build();
    }
    
    return next.execute(value, context);
}
 
Example #8
Source File: AbstractTemporalAccessorParsingProcessor.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws SuperCsvCellProcessorException if value is null or is not a String
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	if( !(value instanceof String) ) {
		throw new SuperCsvCellProcessorException(String.class, value, context, this);
	}

	final String string = (String) value;
	final T result;
	try {
		if( formatter != null ) {
			result = parse(string, formatter);
		} else {
			result = parse(string);
		}
	}
	catch(DateTimeParseException e) {
		throw new SuperCsvCellProcessorException("Failed to parse value", context, this, e);
	}

	return next.execute(result, context);
}
 
Example #9
Source File: LengthMax.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             {@literal if value is null}
 * @throws SuperCsvConstraintViolationException
 *             {@literal if length is < min or length > max}
 */
@SuppressWarnings("unchecked")
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String stringValue = value.toString();
    final int length = stringValue.length();
    if( length > max ) {
        throw createValidationException(context)
            .messageFormat("the length (%d) of value '%s' does not lie the max (%d) values (inclusive)",
                    length, stringValue, max)
            .rejectedValue(stringValue)
            .messageVariables("max", getMax())
            .messageVariables("length", length)
            .build();
            
    }
    
    return next.execute(stringValue, context);
}
 
Example #10
Source File: ParseInterval.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null or is not a String
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	if (!(value instanceof String)) {
		throw new SuperCsvCellProcessorException(String.class, value,
				context, this);
	}
	final Interval result;
	try {
		result = Interval.parse((String) value);
	} catch (IllegalArgumentException e) {
		throw new SuperCsvCellProcessorException(
				"Failed to parse value as an Interval", context, this, e);
	}
	return next.execute(result, context);
}
 
Example #11
Source File: Equals.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvConstraintViolationException
 *             if value isn't equal to the constant value (or previously encountered value if a constant wasn't
 *             supplied)
 */
public Object execute(final Object value, final CsvContext context) {
	if( UNKNOWN.equals(constantValue) ) {
		constantValue = value; // no constant supplied, so remember the first value encountered
	} else {
		if( !equals(constantValue, value) ) {
			if( constantSupplied ) {
				throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the supplied constant '%s'", value,
					constantValue), context, this);
			} else {
				throw new SuperCsvConstraintViolationException(String.format("'%s' is not equal to the previous value(s) of '%s'",
					value, constantValue), context, this);
			}
		}
	}
	return next.execute(value, context);
}
 
Example #12
Source File: LengthBetween.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             {@literal if value is null}
 * @throws SuperCsvConstraintViolationException
 *             {@literal if length is < min or length > max}
 */
@SuppressWarnings("unchecked")
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String stringValue = value.toString();
    final int length = stringValue.length();
    if( length < min || length > max ) {
        throw createValidationException(context)
            .messageFormat("the length (%d) of value '%s' does not lie between the min (%d) and max (%d) values (inclusive)",
                    length, stringValue, min, max)
            .rejectedValue(stringValue)
            .messageVariables("min", getMin())
            .messageVariables("max", getMax())
            .messageVariables("length", length)
            .build();
            
    }
    
    return next.execute(stringValue, context);
}
 
Example #13
Source File: CsvExceptionConverter.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
private List<CsvError> convert(final SuperCsvNoMatchColumnSizeException 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("expectedSize", exception.getEpxpectedColumnSize());
    variables.put("actualSize", exception.getActualColumnSize());
    
    final String defaultMessage = exception.getMessage();
    
    final String errorCode = "csvError.noMatchColumnSize";
    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);
    
}
 
Example #14
Source File: CsvFieldValidator.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * メッセージ変数を取得する。
 * <p>デフォルトの場合、下記の値が設定される。</p>
 * <ul>
 *   <li>lineNumber : カラムの値に改行が含まれている場合を考慮した実際の行番号です。1から始まります。</li>
 *   <li>rowNumber : CSVの行番号です。1から始まります。</li>
 *   <li>columnNumber : CSVの列番号です。1から始まります。</li>
 *   <li>label : カラムの見出し名です。</li>
 *   <li>value : 実際のカラムの値です。</li>
 *   <li>printer : カラムの値に対数するフォーマッタです。{@link TextPrinter#print(Object)}でvalue値を文字列に変換します。</li>
 * </ul>
 * 
 * @param field フィールド情報
 * @return メッセージ変数のマップ。
 */
default Map<String, Object> createMessageVariables(final CsvField<T> field) {
    
    final CsvContext csvContext = field.getValidationContext().getCsvContext();
    
    final Map<String, Object> variables = new HashMap<>();
    variables.put("lineNumber", csvContext.getLineNumber());
    variables.put("rowNumber", csvContext.getRowNumber());
    variables.put("columnNumber", field.getColumnNumber());
    variables.put("label", field.getLabel());
    variables.put("validatedValue", field.getValue());
    variables.put("printer", field.getColumnMapping().getFormatter());
    
    return variables;
    
}
 
Example #15
Source File: DMinMax.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null or can't be parsed as a Double
 * @throws SuperCsvConstraintViolationException
 *             if value doesn't lie between min and max (inclusive)
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	final Double result;
	if( value instanceof Double ) {
		result = (Double) value;
	} else {
		try {
			result = Double.parseDouble(value.toString());
		}
		catch(final NumberFormatException e) {
			throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a Double", value),
				context, this, e);
		}
	}
	
	if( result < min || result > max ) {
		throw new SuperCsvConstraintViolationException(String.format(
			"%f does not lie between the min (%f) and max (%f) values (inclusive)", result, min, max), context,
			this);
	}
	
	return next.execute(result, context);
}
 
Example #16
Source File: ParseEnum.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null or can't be parsed as an Enum
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	final String inputString = value.toString();
	
	for( final Enum<?> enumConstant : enumClass.getEnumConstants() ) {
		String constantName = enumConstant.name();
		if( ignoreCase ? constantName.equalsIgnoreCase(inputString) : constantName.equals(inputString) ) {
			return enumConstant;
		}
	}
	
	throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as a enum of type %s", value,
		enumClass.getName()), context, this);
	
}
 
Example #17
Source File: ParseLong.java    From super-csv with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null, isn't a Long or String, or can't be parsed as a Long
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	final Long result;
	if( value instanceof Long ) {
		result = (Long) value;
	} else if( value instanceof String ) {
		try {
			result = Long.parseLong((String) value);
		}
		catch(final NumberFormatException e) {
			throw new SuperCsvCellProcessorException(String.format("'%s' could not be parsed as an Long", value),
				context, this, e);
		}
	} else {
		final String actualClassName = value.getClass().getName();
		throw new SuperCsvCellProcessorException(String.format(
			"the input value should be of type Long or String but is of type %s", actualClassName), context, this);
	}
	
	return next.execute(result, context);
}
 
Example #18
Source File: PrintProcessor.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    try {
        final String result = printer.print((T)value);
        return next.execute(result, context);
        
    } catch(TextPrintException e) {
        throw createValidationException(context)
            .messageFormat("'%s' could not print.", value.toString())
            .exception(e)
            .rejectedValue(value)
            .build();
    }
    
}
 
Example #19
Source File: CsvExceptionConverter.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
private List<CsvError> convert(final SuperCsvNoMatchHeaderException 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("expectedHeaders", exception.getExpectedHeaders());
    variables.put("actualHeaders", exception.getActualHeaders());
    variables.put("joinedExpectedHeaders", String.join(", ", exception.getExpectedHeaders()));
    variables.put("joinedActualHeaders", String.join(", ", exception.getActualHeaders()));
    
    final String defaultMessage = exception.getMessage();
    
    final String errorCode = "csvError.noMatchHeader";
    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);
    
}
 
Example #20
Source File: CallbackMethodTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@CsvPreWrite
public void handlePreWrite(final TestCsv record, final CsvContext context, 
        final CsvBindingErrors bindingErrors, final Class<?>[] groups, final Point point) {
    
    addMessage("method::handlePreWrite", record);
    record.addMessage("listener::handlePreWrite", record);
    
    assertThat(record).isNotNull();
    assertThat(context).isNotNull();
    assertThat(bindingErrors).isNotNull();
    assertThat(groups).containsExactly(Group1.class, Group2.class);
    assertThat(point).isNull();;
    
}
 
Example #21
Source File: ConvertNullTo.java    From super-csv with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object execute(final Object value, final CsvContext context) {
	if( value == null ) {
		return returnValue;
	}
	
	return next.execute(value, context);
}
 
Example #22
Source File: HashMapper.java    From super-csv with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	Object result = mapping.get(value);
	if( result == null ) {
		result = defaultValue;
	}
	
	return next.execute(result, context);
}
 
Example #23
Source File: WordRequire.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    if(!words.isEmpty()) {
        final String stringValue = value.toString();
        
        final List<String> requiredWords = words.stream()
                .filter(word -> !stringValue.contains(word))
                .collect(Collectors.toList());
        
        if(!requiredWords.isEmpty()) {
            final String joinedWords = String.join(", ", requiredWords);
            throw createValidationException(context)
                .messageFormat("'%s' does not contain any of the required substirng '%s'", stringValue, joinedWords)
                .rejectedValue(stringValue)
                .messageVariables("words", requiredWords)
                .build();
        }
    }
    
    return next.execute(value, context);
}
 
Example #24
Source File: LengthExact.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             {@literal if value is null}
 * @throws SuperCsvConstraintViolationException
 *             {@literal if length is < min or length > max}
 */
@SuppressWarnings("unchecked")
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String stringValue = value.toString();
    final int length = stringValue.length();
    
    if( !requriedLengths.contains(length)) {
        final String joinedLength = requriedLengths.stream()
                .map(String::valueOf).collect(Collectors.joining(", "));
        
        throw createValidationException(context)
            .messageFormat("the length (%d) of value '%s' not any of required lengths (%s)",
                    length, stringValue, joinedLength)
            .rejectedValue(stringValue)
            .messageVariables("length", length)
            .messageVariables("requiredLengths", getRequiredLengths())
            .build();
            
    }
    
    return next.execute(stringValue, context);
}
 
Example #25
Source File: Require.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execute(final Object value, final CsvContext context) {
    
    if (!validate(value)){
        throw createValidationException(context)
            .message("null or empty value encountered")
            .messageVariables("considerEmpty", considerEmpty)
            .messageVariables("considerBlank", considerBlank)
            .rejectedValue(value)
            .build();
    }
    
    return next.execute(value, context);
}
 
Example #26
Source File: IsIncludedIn.java    From super-csv with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws SuperCsvCellProcessorException
 *             if value is null
 * @throws SuperCsvConstraintViolationException
 *             if value isn't one of the possible values
 */
public Object execute(final Object value, final CsvContext context) {
	validateInputNotNull(value, context);
	
	if( !possibleValues.contains(value) ) {
		throw new SuperCsvConstraintViolationException(String.format(
			"'%s' is not included in the allowed set of values", value), context, this);
	}
	
	return next.execute(value, context);
}
 
Example #27
Source File: ParseIconColour.java    From super-csv with Apache License 2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
	public Object execute(Object value, CsvContext context) {
		
		validateInputNotNull(value, context);
		
		for( IconColour colour : IconColour.values() ) {
			if( colour.name().equalsIgnoreCase(value.toString()) ) {
				return next.execute(colour, context);
			}
		}
		
		throw new SuperCsvCellProcessorException(String.format("Unknown IconColour: %s", value), context, this);

}
 
Example #28
Source File: DateTimeMin.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final Class<?> exepectedClass = getMin().getClass();
    if(!exepectedClass.isAssignableFrom(value.getClass())) {
        throw new SuperCsvCellProcessorException(exepectedClass, value, context, this);
    }
    
    final T result = (T) value;
    if(!validate(result)) {
        throw createValidationException(context)
            .messageFormat("%s does not lie the min (%s) value.", 
                    printValue(result), printValue(min))
            .rejectedValue(value)
            .messageVariables("min", getMin())
            .messageVariables("inclusive", isInclusive())
            .messageVariables("printer", getPrinter())
            .build();
            
    }   
    
    return next.execute(result, context);
}
 
Example #29
Source File: CallbackMethodTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@CsvPostRead
public void handlePostRead(final TestCsv record, final CsvContext context, 
        final CsvBindingErrors bindingErrors, final Class<?>[] groups, final Point point) {
    
    addMessage("method::handlePostRead", record);
    
    assertThat(record).isNotNull()
        .hasNoNullFieldsOrProperties();
    assertThat(context).isNotNull()
        .hasNoNullFieldsOrProperties();
    assertThat(bindingErrors).isNotNull();
    assertThat(groups).containsExactly(Group1.class, Group2.class);
    assertThat(point).isNull();;
    
}
 
Example #30
Source File: Trim.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Object execute(final Object value, final CsvContext context) {
    
    if(value == null) {
        return next.execute(value, context);
    }
    
    final String result = value.toString().trim();
    return next.execute(result, context);
}