T
- Type of object that is being processed.C
- The type of the internal many-to-one mappingI
- The initializer type used to build the internal many-to-one mappingK
- The type of the key used for internal indexingpublic abstract class AbstractMappingStrategy<I,K extends Comparable<K>,C extends ComplexFieldMapEntry<I,K,T>,T> extends Object implements MappingStrategy<T>
This mapping strategy knows of the existence of binding annotations, but
assumes through getBindingAnnotations()
they are not in use.
Anyone is welcome to use it as a base class for their own mapping strategies.
Modifier and Type | Class and Description |
---|---|
protected static class |
AbstractMappingStrategy.RecursiveType
Encapsulates a bean type and all of the member variables that need to be
recursed into.
|
Modifier and Type | Field and Description |
---|---|
protected Locale |
errorLocale
Locale for error messages.
|
protected HeaderIndex |
headerIndex
Maintains a bi-directional mapping between column position(s) and header
name.
|
protected String |
profile
The profile for configuring bean fields.
|
protected AbstractMappingStrategy.RecursiveType |
recursiveTypeTree
A tree of the types encountered during recursion through the root bean
type.
|
protected Class<? extends T> |
type
This is the class of the bean to be manipulated.
|
Constructor and Description |
---|
AbstractMappingStrategy() |
Modifier and Type | Method and Description |
---|---|
protected abstract K |
chooseMultivaluedFieldIndexFromHeaderIndex(int index)
For
BeanField.indexAndSplitMultivaluedField(java.lang.Object, java.lang.Object)
it is necessary to determine which index to pass in. |
protected Map<Class<?>,Object> |
createBean()
Implementation will return a bean of the type of object being mapped.
|
protected CsvConverter |
determineConverter(Field field,
Class<?> elementType,
String locale,
String writeLocale,
Class<? extends AbstractCsvConverter> customConverter)
Given the information provided, determines the appropriate built-in
converter to be passed in to the
BeanField being created. |
protected List<Field> |
filterIgnoredFields(Class<?> type,
Field[] fields)
Filters all fields that opencsv has been instructed to ignore and
returns a list of the rest.
|
protected abstract BeanField<T,K> |
findField(int col)
Gets the field for a given column position.
|
abstract String |
findHeader(int col)
Gets the name (or position number) of the header for the given column
number.
|
String[] |
generateHeader(T bean)
This method generates a header that can be used for writing beans of the
type provided back to a file.
|
protected Set<Class<? extends Annotation>> |
getBindingAnnotations()
Returns a set of the annotations that are used for binding in this
mapping strategy.
|
protected String |
getColumnName(int col)
Get the column name for a given column position.
|
protected abstract FieldMap<I,K,? extends C,T> |
getFieldMap()
Returns the
FieldMap associated with this mapping strategy. |
Class<? extends T> |
getType()
Get the class type that the strategy is mapping.
|
void |
ignoreFields(org.apache.commons.collections4.MultiValuedMap<Class<?>,Field> fields)
When processing a bean for reading or writing, ignore the given fields
from the given classes completely, including all annotations and
requirements.
|
protected Map<Class<?>,Object> |
indexBean(T bean)
Creates an index of necessary types according to the mapping strategy
and existing instances of (subordinate) beans.
|
protected abstract void |
initializeFieldMap()
Creates an empty binding-type-specific field map that can be filled in
later steps.
|
protected BeanField<T,K> |
instantiateCustomConverter(Class<? extends AbstractBeanField<T,K>> converter)
Attempts to instantiate the class of the custom converter specified.
|
protected boolean |
isForbiddenClassForRecursion(Class<?> type) |
protected void |
loadAnnotatedFieldMap(org.apache.commons.collections4.ListValuedMap<Class<?>,Field> fields)
Creates a map of annotated fields in the bean to be processed.
|
protected void |
loadFieldMap()
Builds a map of columns from the input to fields of the bean type.
|
protected AbstractMappingStrategy.RecursiveType |
loadRecursiveClasses(Class<?> newType,
Set<Class<?>> encounteredTypes)
Creates a tree of beans embedded in each other.
|
protected abstract void |
loadUnadornedFieldMap(org.apache.commons.collections4.ListValuedMap<Class<?>,Field> fields)
Creates a map of fields in the bean to be processed that have no
annotations.
|
protected Map<Boolean,org.apache.commons.collections4.ListValuedMap<Class<?>,Field>> |
partitionFields()
Partitions all non-synthetic fields of the bean type being processed
into annotated and non-annotated fields according to
getBindingAnnotations() . |
T |
populateNewBean(String[] line)
Takes a line of input from a CSV file and creates a bean out of it.
|
protected <A extends Annotation> |
selectAnnotationForProfile(A[] annotations,
Function<A,String[]> getProfiles)
Determines which one of a list of annotations applies to the currently
selected profile.
|
void |
setErrorLocale(Locale errorLocale)
Sets the locale for all error messages.
|
protected void |
setFieldValue(Map<Class<?>,Object> beanTree,
String value,
int column)
Populates the field corresponding to the column position indicated of the
bean passed in according to the rules of the mapping strategy.
|
void |
setProfile(String profile)
Sets the profile this mapping strategy will use when configuring bean
fields.
|
void |
setType(Class<? extends T> type)
Sets the class type that is being mapped.
|
String[] |
transmuteBean(T bean)
Transmutes a bean instance into an array of
String s to be written
to a CSV file. |
protected abstract void |
verifyLineLength(int numberOfFields)
Must be called once the length of input for a line/record is known to
verify that the line was complete.
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
captureHeader, isAnnotationDriven
protected final HeaderIndex headerIndex
protected AbstractMappingStrategy.RecursiveType recursiveTypeTree
CsvRecurse
.protected Locale errorLocale
protected String profile
protected abstract K chooseMultivaluedFieldIndexFromHeaderIndex(int index)
BeanField.indexAndSplitMultivaluedField(java.lang.Object, java.lang.Object)
it is necessary to determine which index to pass in.index
- The current column position while transmuting a bean to CSV
outputBeanField.indexAndSplitMultivaluedField(java.lang.Object, java.lang.Object)
protected abstract FieldMap<I,K,? extends C,T> getFieldMap()
FieldMap
associated with this mapping strategy.FieldMap
used by this strategyprotected Set<Class<? extends Annotation>> getBindingAnnotations()
CsvBindByName
or
CsvBindByPosition
that are relevant for binding input fields to
bean members in this mapping strategyprotected void loadAnnotatedFieldMap(org.apache.commons.collections4.ListValuedMap<Class<?>,Field> fields)
This method is called by loadFieldMap()
when at least one
relevant annotation is found on a member variable.
The default implementation assumes there are no annotations and does nothing.
fields
- A list of fields annotated with a binding annotation
in the bean to be processedprotected abstract void loadUnadornedFieldMap(org.apache.commons.collections4.ListValuedMap<Class<?>,Field> fields)
loadFieldMap()
when absolutely no
annotations that are relevant for this mapping strategy are found in the
type of bean being processed.fields
- A list of all non-synthetic fields in the bean to be
processedprotected abstract void initializeFieldMap()
This method may be called multiple times and must erase any state information from previous calls.
protected abstract BeanField<T,K> findField(int col)
col
- The column to find the field forCsvBadConverterException
- If a custom converter for a field cannot
be initializedprotected abstract void verifyLineLength(int numberOfFields) throws CsvRequiredFieldEmptyException
numberOfFields
- The number of fields present in the line of inputCsvRequiredFieldEmptyException
- If a required column is missingprotected Map<Class<?>,Object> createBean() throws CsvBeanIntrospectionException, IllegalStateException
CsvBeanIntrospectionException
- Thrown on error creating object.IllegalStateException
- If the type of the bean has not been
initialized through setType(java.lang.Class)
protected Map<Class<?>,Object> indexBean(T bean) throws IllegalAccessException, InvocationTargetException
bean
- The root bean to be indexedIllegalAccessException
- If there are problems accessing a
subordinate beanInvocationTargetException
- If there are problems accessing a
subordinate beanpublic abstract String findHeader(int col)
col
- The column number for which the header is soughtpublic String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException
The ordering of the headers is determined by the
FieldMap
in use.
This method should be called first by all overriding classes to make
certain headerIndex
is properly initialized.
generateHeader
in interface MappingStrategy<T>
bean
- One fully populated bean from which the header can be derived.
This is important in the face of joining and splitting. If we have a
MultiValuedMap as a field that is the target for a join on reading, that
same field must be split into multiple columns on writing. Since the
joining is done via regular expressions, it is impossible for opencsv
to know what the column names are supposed to be on writing unless this
bean includes a fully populated map.null
.CsvRequiredFieldEmptyException
- If a required header is missing
while attempting to write. Since every other header is hard-wired
through the bean fields and their associated annotations, this can only
happen with multi-valued fields.protected String getColumnName(int col)
col
- Column position.public Class<? extends T> getType()
MappingStrategy
will create.public T populateNewBean(String[] line) throws CsvBeanIntrospectionException, CsvFieldAssignmentException, CsvChainedException
MappingStrategy
populateNewBean
in interface MappingStrategy<T>
line
- A line of input returned from CSVReader
CsvBeanIntrospectionException
- Generally, if some part of the bean cannot
be accessed and used as neededCsvFieldAssignmentException
- A more specific subclass of this
exception is thrown for any problem decoding and assigning a field
of the input to a bean fieldCsvChainedException
- If multiple exceptions are thrown for the
same input linepublic void setType(Class<? extends T> type) throws CsvBadConverterException
setType
in interface MappingStrategy<T>
type
- Class type.CsvBadConverterException
- If a field in the bean is annotated
with a custom converter that cannot be initialized. If you are not
using custom converters that you have written yourself, it should be
safe to catch this exception and ignore it.public void setProfile(String profile)
setProfile
in interface MappingStrategy<T>
profile
- The profile to usepublic void ignoreFields(org.apache.commons.collections4.MultiValuedMap<Class<?>,Field> fields) throws IllegalArgumentException
MappingStrategy
When processing a bean for reading or writing, ignore the given fields from the given classes completely, including all annotations and requirements. This method has two compelling applications:
Calling this method overwrites the fields passed in from any previous
calls. It is legal to call this method before calling
MappingStrategy.setType(Class)
, and it may be more efficient to do so.
Caution must be exercised with this method when letting opencsv
automatically determine the mapping strategy. When a field is ignored,
opencsv pretends it does not exist at all. If, for instance, all fields
annotated with opencsv binding annotations are ignored, opencsv will
automatically switch to HeaderColumnNameMappingStrategy
and
assume header names exactly match field names.
An implementation of this interface is not required to implement this
method. The default implementation throws
UnsupportedOperationException
.
ignoreFields
in interface MappingStrategy<T>
fields
- All fields to be ignored, mapped from the classes of which
they are members. These are the classes as opencsv
encounters them, not necessarily the declaring classes if
any fields are inherited. May be null
.IllegalArgumentException
- If any entry in the map has a
null
key, a null
value, or if the value is not a field
in the class represented by the keyCsvIgnore
protected List<Field> filterIgnoredFields(Class<?> type, Field[] fields)
type
- The class from which fields
come. This must be the
class as opencsv would seek to instantiate it, which in the
case of inheritance is not necessarily the declaring class.fields
- The fields to be filteredprotected void loadFieldMap() throws CsvBadConverterException
CsvBadConverterException
- If there is a problem instantiating the
custom converter for an annotated fieldprotected boolean isForbiddenClassForRecursion(Class<?> type)
type
- Class to be checkedfalse
), or
must be considered a leaf node for recursion (true
). This
implementation considers the boxed primitives forbidden.protected AbstractMappingStrategy.RecursiveType loadRecursiveClasses(Class<?> newType, Set<Class<?>> encounteredTypes)
CsvRecurse
and
their associated types. This method is used recursively.newType
- The type that is meant to be added to the treeencounteredTypes
- A set of types already encountered during
recursion, as types may not be recursed into
more than once.CsvRecursionException
- If recursion is attempted into a primitive
type or a previously encountered type is added again or a member
variable annotated with CsvRecurse
is also annotated with a
binding annotationprotected Map<Boolean,org.apache.commons.collections4.ListValuedMap<Class<?>,Field>> partitionFields()
getBindingAnnotations()
.Boolean.TRUE
, and
all non-annotated fields are mapped under Boolean.FALSE
.protected BeanField<T,K> instantiateCustomConverter(Class<? extends AbstractBeanField<T,K>> converter) throws CsvBadConverterException
converter
- The class for a custom converterCsvBadConverterException
- If the class cannot be instantiatedpublic void setErrorLocale(Locale errorLocale)
MappingStrategy
setErrorLocale
in interface MappingStrategy<T>
errorLocale
- Locale for error messages. If null, the default locale
is used.protected void setFieldValue(Map<Class<?>,Object> beanTree, String value, int column) throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException, CsvConstraintViolationException, CsvValidationException
beanTree
- Object containing the field to be set.value
- String containing the value to set the field to.column
- The column position from the CSV file under which this
value was found.CsvDataTypeMismatchException
- When the result of data conversion returns
an object that cannot be assigned to the selected fieldCsvRequiredFieldEmptyException
- When a field is mandatory, but there is no
input datum in the CSV fileCsvConstraintViolationException
- When the internal structure of
data would be violated by the data in the CSV fileCsvValidationException
- If a user-supplied validator determines
that the input is invalidpublic String[] transmuteBean(T bean) throws CsvFieldAssignmentException, CsvChainedException
MappingStrategy
String
s to be written
to a CSV file.transmuteBean
in interface MappingStrategy<T>
bean
- The bean to be transmutedCSVWriter
CsvFieldAssignmentException
- A more specific subclass of this
exception is thrown for any problem decoding and assigning a field
of the input to a bean fieldCsvChainedException
- If multiple exceptions are thrown for the
same input lineprotected CsvConverter determineConverter(Field field, Class<?> elementType, String locale, String writeLocale, Class<? extends AbstractCsvConverter> customConverter) throws CsvBadConverterException
BeanField
being created.field
- The field of the bean type in questionelementType
- The type to be generated by the converter (on reading)locale
- The locale for conversion on reading. May be null or an
empty string if a locale is not in use.writeLocale
- The locale for conversion on writing. May be null or
an empty string if a locale is not in use.customConverter
- An optional custom converterCsvBadConverterException
- If the converter cannot be instantiatedprotected <A extends Annotation> A selectAnnotationForProfile(A[] annotations, Function<A,String[]> getProfiles)
null
is
returned.A
- The annotation type being testedannotations
- All annotations of a given typegetProfiles
- A function mapping an annotation of type A
to
the list of profiles it applies tonull
if
nothing appropriate is foundCopyright © 2005–2023. All rights reserved.