Search in sources :

Example 16 with Field

use of java.lang.reflect.Field in project camel by apache.

the class BindyCsvFactory method initAnnotatedFields.

@Override
public void initAnnotatedFields() {
    maxpos = 0;
    for (Class<?> cl : models) {
        List<Field> linkFields = new ArrayList<Field>();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Class retrieved: {}", cl.getName());
        }
        for (Field field : cl.getDeclaredFields()) {
            DataField dataField = field.getAnnotation(DataField.class);
            if (dataField != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Position defined in the class: {}, position: {}, Field: {}", new Object[] { cl.getName(), dataField.pos(), dataField });
                }
                if (dataField.required()) {
                    ++numberMandatoryFields;
                } else {
                    ++numberOptionalFields;
                }
                int pos = dataField.pos();
                if (annotatedFields.containsKey(pos)) {
                    Field f = annotatedFields.get(pos);
                    LOG.warn("Potentially invalid model: existing @DataField '{}' replaced by '{}'", f.getName(), field.getName());
                }
                dataFields.put(pos, dataField);
                annotatedFields.put(pos, field);
                maxpos = Math.max(maxpos, pos);
            }
            Link linkField = field.getAnnotation(Link.class);
            if (linkField != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Class linked: {}, Field: {}", cl.getName(), field);
                }
                linkFields.add(field);
            }
        }
        if (!linkFields.isEmpty()) {
            annotatedLinkFields.put(cl.getName(), linkFields);
        }
        totalFields = numberMandatoryFields + numberOptionalFields;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Number of optional fields: {}", numberOptionalFields);
            LOG.debug("Number of mandatory fields: {}", numberMandatoryFields);
            LOG.debug("Total: {}", totalFields);
        }
    }
    if (annotatedFields.size() < maxpos) {
        LOG.info("Potentially incomplete model: some csv fields may not be mapped to @DataField members");
    }
}
Also used : Field(java.lang.reflect.Field) DataField(org.apache.camel.dataformat.bindy.annotation.DataField) DataField(org.apache.camel.dataformat.bindy.annotation.DataField) ArrayList(java.util.ArrayList) Link(org.apache.camel.dataformat.bindy.annotation.Link)

Example 17 with Field

use of java.lang.reflect.Field in project camel by apache.

the class BindyFixedLengthFactory method bind.

public void bind(String record, Map<String, Object> model, int line) throws Exception {
    int pos = 1;
    int counterMandatoryFields = 0;
    DataField dataField;
    String token;
    int offset = 1;
    int length;
    String delimiter;
    Field field;
    // Iterate through the list of positions
    // defined in the @DataField
    // and grab the data from the line
    Collection<DataField> c = dataFields.values();
    Iterator<DataField> itr = c.iterator();
    // this iterator is for a link list that was built using items in order
    while (itr.hasNext()) {
        dataField = itr.next();
        length = dataField.length();
        delimiter = dataField.delimiter();
        if (length == 0 && dataField.lengthPos() != 0) {
            Field lengthField = annotatedFields.get(dataField.lengthPos());
            lengthField.setAccessible(true);
            Object modelObj = model.get(lengthField.getDeclaringClass().getName());
            Object lengthObj = lengthField.get(modelObj);
            length = ((Integer) lengthObj).intValue();
        }
        if (length < 1 && delimiter == null && dataField.lengthPos() == 0) {
            throw new IllegalArgumentException("Either length or delimiter must be specified for the field : " + dataField.toString());
        }
        if (offset - 1 <= -1) {
            throw new IllegalArgumentException("Offset/Position of the field " + dataField.toString() + " cannot be negative");
        }
        // skip ahead if the expected position is greater than the offset
        if (dataField.pos() > offset) {
            LOG.debug("skipping ahead [" + (dataField.pos() - offset) + "] chars.");
            offset = dataField.pos();
        }
        if (length > 0) {
            if (record.length() < offset) {
                token = "";
            } else {
                int endIndex = offset + length - 1;
                if (endIndex > record.length()) {
                    endIndex = record.length();
                }
                token = record.substring(offset - 1, endIndex);
            }
            offset += length;
        } else if (!delimiter.equals("")) {
            String tempToken = record.substring(offset - 1, record.length());
            token = tempToken.substring(0, tempToken.indexOf(delimiter));
            // include the delimiter in the offset calculation
            offset += token.length() + 1;
        } else {
            // defined as a zero-length field
            token = "";
        }
        if (dataField.trim()) {
            token = trim(token, dataField, paddingChar);
        //token = token.trim();
        }
        // Check mandatory field
        if (dataField.required()) {
            // Increment counter of mandatory fields
            ++counterMandatoryFields;
            // This is not possible for mandatory fields
            if (token.equals("")) {
                throw new IllegalArgumentException("The mandatory field defined at the position " + pos + " is empty for the line: " + line);
            }
        }
        // Get Field to be set
        field = annotatedFields.get(dataField.pos());
        field.setAccessible(true);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Pos/Offset: {}, Data: {}, Field type: {}", new Object[] { offset, token, field.getType() });
        }
        // Create format object to format the field
        FormattingOptions formattingOptions = ConverterUtils.convert(dataField, field.getType(), field.getAnnotation(BindyConverter.class), getLocale());
        Format<?> format = formatFactory.getFormat(formattingOptions);
        // field object to be set
        Object modelField = model.get(field.getDeclaringClass().getName());
        // format the data received
        Object value = null;
        if ("".equals(token)) {
            token = dataField.defaultValue();
        }
        if (!"".equals(token)) {
            try {
                value = format.parse(token);
            } catch (FormatException ie) {
                throw new IllegalArgumentException(ie.getMessage() + ", position: " + offset + ", line: " + line, ie);
            } catch (Exception e) {
                throw new IllegalArgumentException("Parsing error detected for field defined at the position/offset: " + offset + ", line: " + line, e);
            }
        } else {
            value = getDefaultValueForPrimitive(field.getType());
        }
        field.set(modelField, value);
        ++pos;
    }
    // check for unmapped non-whitespace data at the end of the line
    if (offset <= record.length() && !(record.substring(offset - 1, record.length())).trim().equals("") && !isIgnoreTrailingChars()) {
        throw new IllegalArgumentException("Unexpected / unmapped characters found at the end of the fixed-length record at line : " + line);
    }
    LOG.debug("Counter mandatory fields: {}", counterMandatoryFields);
    if (pos < totalFields) {
        throw new IllegalArgumentException("Some fields are missing (optional or mandatory), line: " + line);
    }
    if (counterMandatoryFields < numberMandatoryFields) {
        throw new IllegalArgumentException("Some mandatory fields are missing, line: " + line);
    }
}
Also used : BindyConverter(org.apache.camel.dataformat.bindy.annotation.BindyConverter) FormatException(org.apache.camel.dataformat.bindy.format.FormatException) FormatException(org.apache.camel.dataformat.bindy.format.FormatException) Field(java.lang.reflect.Field) DataField(org.apache.camel.dataformat.bindy.annotation.DataField) DataField(org.apache.camel.dataformat.bindy.annotation.DataField)

Example 18 with Field

use of java.lang.reflect.Field in project camel by apache.

the class ReflectionHelper method doWithFields.

/**
     * Invoke the given callback on all fields in the target class, going up the
     * class hierarchy to get all declared fields.
     * @param clazz the target class to analyze
     * @param fc the callback to invoke for each field
     */
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException {
    // Keep backing up the inheritance hierarchy.
    Class<?> targetClass = clazz;
    do {
        Field[] fields = targetClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                fc.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException("Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);
}
Also used : Field(java.lang.reflect.Field)

Example 19 with Field

use of java.lang.reflect.Field in project camel by apache.

the class IOConverterCharsetTest method switchToDefaultCharset.

private void switchToDefaultCharset(String charset) {
    try {
        Field defaultCharset = Charset.class.getDeclaredField("defaultCharset");
        defaultCharset.setAccessible(true);
        defaultCharset.set(null, Charset.forName(charset));
    } catch (Exception e) {
    // Do nothing here
    }
}
Also used : Field(java.lang.reflect.Field)

Example 20 with Field

use of java.lang.reflect.Field in project camel by apache.

the class BindyKeyValuePairFactory method unbind.

/**
     *
     */
@Override
public String unbind(Map<String, Object> model) throws Exception {
    StringBuilder builder = new StringBuilder();
    Map<Integer, KeyValuePairField> keyValuePairFieldsSorted = new TreeMap<Integer, KeyValuePairField>(keyValuePairFields);
    Iterator<Integer> it = keyValuePairFieldsSorted.keySet().iterator();
    // Map containing the OUT position of the field
    // The key is double and is created using the position of the field and
    // location of the class in the message (using section)
    Map<Integer, String> positions = new TreeMap<Integer, String>();
    // Check if separator exists
    ObjectHelper.notNull(this.pairSeparator, "The pair separator has not been instantiated or property not defined in the @Message annotation");
    char separator = ConverterUtils.getCharDelimiter(this.getPairSeparator());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Separator converted: '0x{}', from: {}", Integer.toHexString(separator), this.getPairSeparator());
    }
    while (it.hasNext()) {
        KeyValuePairField keyValuePairField = keyValuePairFieldsSorted.get(it.next());
        ObjectHelper.notNull(keyValuePairField, "KeyValuePair");
        // Retrieve the field
        Field field = annotatedFields.get(keyValuePairField.tag());
        // Change accessibility to allow to read protected/private fields
        field.setAccessible(true);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Tag: {}, Field type: {}, class: {}", new Object[] { keyValuePairField.tag(), field.getType(), field.getDeclaringClass().getName() });
        }
        // Retrieve the format, pattern and precision associated to the type
        Class<?> type = field.getType();
        // Create format
        FormattingOptions formattingOptions = ConverterUtils.convert(keyValuePairField, field.getType(), field.getAnnotation(BindyConverter.class), getLocale());
        Format<Object> format = (Format<Object>) formatFactory.getFormat(formattingOptions);
        // Get object to be formatted
        Object obj = model.get(field.getDeclaringClass().getName());
        if (obj != null) {
            // Get field value
            Object keyValue = field.get(obj);
            if (this.isMessageOrdered()) {
                // Generate a key using the number of the section
                // and the position of the field
                Integer key1 = sections.get(obj.getClass().getName());
                Integer key2 = keyValuePairField.position();
                LOG.debug("Key of the section: {}, and the field: {}", key1, key2);
                Integer keyGenerated = generateKey(key1, key2);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Key generated: {}, for section: {}", String.valueOf(keyGenerated), key1);
                }
                // Add value to the list if not null
                if (keyValue != null) {
                    // Format field value
                    String valueFormatted;
                    try {
                        valueFormatted = format.format(keyValue);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Formatting error detected for the tag: " + keyValuePairField.tag(), e);
                    }
                    // Create the key value string
                    String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormatted;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Value to be formatted: {}, for the tag: {}, and its formatted value: {}", new Object[] { keyValue, keyValuePairField.tag(), valueFormatted });
                    }
                    // Add the content to the TreeMap according to the
                    // position defined
                    positions.put(keyGenerated, value);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Positions size: {}", positions.size());
                    }
                }
            } else {
                // Add value to the list if not null
                if (keyValue != null) {
                    // Format field value
                    String valueFormatted;
                    try {
                        valueFormatted = format.format(keyValue);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Formatting error detected for the tag: " + keyValuePairField.tag(), e);
                    }
                    // Create the key value string
                    String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormatted + separator;
                    // Add content to the stringBuilder
                    builder.append(value);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Value added: {}{}{}{}", new Object[] { keyValuePairField.tag(), this.getKeyValuePairSeparator(), valueFormatted, separator });
                    }
                }
            }
        }
    }
    // the message according to the order/position
    if (this.isMessageOrdered()) {
        Iterator<Integer> posit = positions.keySet().iterator();
        while (posit.hasNext()) {
            String value = positions.get(posit.next());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Value added at the position ({}) : {}{}", new Object[] { posit, value, separator });
            }
            builder.append(value + separator);
        }
    }
    return builder.toString();
}
Also used : BindyConverter(org.apache.camel.dataformat.bindy.annotation.BindyConverter) TreeMap(java.util.TreeMap) Field(java.lang.reflect.Field) KeyValuePairField(org.apache.camel.dataformat.bindy.annotation.KeyValuePairField) KeyValuePairField(org.apache.camel.dataformat.bindy.annotation.KeyValuePairField)

Aggregations

Field (java.lang.reflect.Field)4517 Method (java.lang.reflect.Method)500 Test (org.junit.Test)475 ArrayList (java.util.ArrayList)434 IOException (java.io.IOException)276 HashMap (java.util.HashMap)263 Map (java.util.Map)253 List (java.util.List)146 InvocationTargetException (java.lang.reflect.InvocationTargetException)136 Pattern (java.util.regex.Pattern)121 Matcher (java.util.regex.Matcher)115 File (java.io.File)93 HashSet (java.util.HashSet)91 Support_Field (tests.support.Support_Field)82 Annotation (java.lang.annotation.Annotation)77 Collection (java.util.Collection)70 SienaException (siena.SienaException)65 Test (org.testng.annotations.Test)64 Before (org.junit.Before)61 Type (java.lang.reflect.Type)57