Example usage for java.lang.reflect Array getLength

List of usage examples for java.lang.reflect Array getLength

Introduction

In this page you can find the example usage for java.lang.reflect Array getLength.

Prototype

@HotSpotIntrinsicCandidate
public static native int getLength(Object array) throws IllegalArgumentException;

Source Link

Document

Returns the length of the specified array object, as an int .

Usage

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*from   ww w . jav  a 2s. c o  m*/
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

From source file:com.astamuse.asta4d.data.DefaultDataTypeTransformer.java

private List<DataValueConvertor> extractConvertors(final Class<?> srcType, final Class<?> targetType) {

    List<DataValueConvertor> foundConvertorList = new LinkedList<DataValueConvertor>();

    // find in list as element to element
    for (DataValueConvertor convertor : DataTypeConvertorList) {
        Pair<Class, Class> typePair = extractConvertorTypeInfo(convertor);
        if (typePair == null) {
            continue;
        }//from   w  w w . j  a va  2 s .c o  m
        if (typePair.getLeft().isAssignableFrom(srcType)) {
            if (targetType.isAssignableFrom(typePair.getRight())) {// found one
                foundConvertorList.add(convertor);
            } else if (convertor instanceof DataValueConvertorTargetTypeConvertable
                    && typePair.getRight().isAssignableFrom(targetType)) {
                foundConvertorList
                        .add(((DataValueConvertorTargetTypeConvertable) convertor).convert(targetType));
            }
        }
        // @formatter:on
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to array
    if (srcType.isArray() && targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(),
                targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }

                                int length = Array.getLength(obj);
                                Object targetArray = Array.newInstance(targetType.getComponentType(), length);

                                for (int i = 0; i < length; i++) {
                                    Array.set(targetArray, i, originalConvertor.convert(Array.get(obj, i)));
                                }
                                return targetArray;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as element to array
    if (targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType, targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            private Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }
                                Object array = Array.newInstance(targetType.getComponentType(), 1);
                                Array.set(array, 0, originalConvertor.convert(obj));
                                return array;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to element
    if (srcType.isArray()) {
        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType);
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                int length = Array.getLength(obj);
                                if (length == 0) {
                                    return null;
                                } else {
                                    return originalConvertor.convert(Array.get(obj, 0));
                                }
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    return foundConvertorList;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONObject serializeJSONObject(JSONSerializable obj)
        throws JSONSerializationException, JSONException {
    if (obj instanceof JSONExternalizable) {
        return ((JSONExternalizable) obj).toJSON();
    }//  w ww.  j  a  v  a2s  .com

    JSONObject jsonObj = new JSONObject();
    Class clz = obj.getClass();
    Field[] fields = clz.getDeclaredFields();

    for (int i = 0; i < fields.length; ++i) {
        fields[i].setAccessible(true);
        int modifiers = fields[i].getModifiers();
        if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
            String name = fields[i].getName();
            Class type = fields[i].getType();

            try {
                Object value = fields[i].get(obj);

                if (type.isArray() && value != null) {
                    int len = Array.getLength(value);

                    Class cls = type.getComponentType();

                    JSONArray array = new JSONArray();

                    for (int k = 0; k < len; ++k) {
                        dumpObject(array, cls, value, k);
                    }
                    jsonObj.put(name, array);
                } else {
                    dumpObject(jsonObj, fields[i], obj);
                }
            } catch (Exception e) {
                throw new JSONSerializationException(e.getMessage(), e);
            }
        }
    }

    return jsonObj;
}

From source file:ArrayUtils.java

/**
 * Merges all elements of a set of arrays into a single array with no
 * duplicates. For primitive types.//from w  w w .  j  a va  2 s .  c om
 * 
 * @param type
 *            The type of the result
 * @param arrays
 *            The arrays to merge
 * @return A new array containing all elements of <code>array1</code> and
 *         all elements of <code>array2</code> that are not present in
 *         <code>array1</code>
 * @throws NullPointerException
 *             If either array is null
 * @throws ArrayStoreException
 *             If elements in the arrays are incompatible with
 *             <code>type</code>
 */
public static Object mergeInclusiveP(Class<?> type, Object... arrays) {
    java.util.LinkedHashSet<Object> set = new java.util.LinkedHashSet<Object>();
    int i, j;
    for (i = 0; i < arrays.length; i++) {
        int len = Array.getLength(arrays[i]);
        for (j = 0; j < len; j++)
            set.add(Array.get(arrays[i], j));
    }
    Object ret = Array.newInstance(type, set.size());
    i = 0;
    for (Object el : set) {
        put(ret, el, i);
        i++;
    }
    return ret;
}

From source file:com.facebook.LegacyTokenCacheTest.java

private static void assertArrayEquals(Object a1, Object a2) {
    assertNotNull(a1);//from w  w  w.j  a va 2s .co  m
    assertNotNull(a2);
    assertEquals(a1.getClass(), a2.getClass());
    assertTrue("Not an array", a1.getClass().isArray());

    int length = Array.getLength(a1);
    assertEquals(length, Array.getLength(a2));
    for (int i = 0; i < length; i++) {
        Object a1Value = Array.get(a1, i);
        Object a2Value = Array.get(a2, i);

        assertEquals(a1Value, a2Value);
    }
}

From source file:org.apache.velocity.tools.generic.DisplayTool.java

/**
 * Formats a specified property of collection or array of objects into the
 * form "A&lt;delim&gt;B&lt;finaldelim&gt;C".
 * //  w  ww  .  jav  a 2s  . c o m
 * @param list A collection or array.
 * @param delim A String.
 * @param finaldelim A String.
 * @param property An object property to format.
 * @return A String.
 */
public String list(Object list, String delim, String finaldelim, String property) {
    if (list == null) {
        return null;
    }
    if (list instanceof Collection) {
        return format((Collection) list, delim, finaldelim, property);
    }
    Collection items;
    if (list.getClass().isArray()) {
        int size = Array.getLength(list);
        items = new ArrayList(size);
        for (int i = 0; i < size; i++) {
            items.add(Array.get(list, i));
        }
    } else {
        items = Collections.singletonList(list);
    }
    return format(items, delim, finaldelim, property);
}

From source file:org.paxml.tag.sql.DdlTag.java

private String[] getArray(Object value) {
    if (value == null) {
        return new String[0];
    }//www.j  ava2  s .  com

    Iterator it = null;

    if (value instanceof Iterable) {
        it = ((Iterable) value).iterator();
    } else if (value instanceof Iterator) {
        it = (Iterator) value;
    } else if (value.getClass().isArray()) {
        int len = Array.getLength(value);
        List<String> list = new ArrayList<String>(len);
        for (int i = 0; i < len; i++) {
            Object item = Array.get(value, i);
            if (item != null) {
                list.add(item.toString());
            }
        }
        return list.toArray(new String[list.size()]);
    }

    if (it != null) {
        List<String> list = new ArrayList<String>();
        while (it.hasNext()) {
            Object next = it.next();
            if (next != null) {
                list.add(next.toString());
            }
        }
        return list.toArray(new String[list.size()]);
    }

    return new String[] { value.toString() };

}

From source file:ArraysX.java

/** Clones an array.
 *//*  w  ww.j  a va2 s .co  m*/
public static final Object clone(Object ary) {
    final int size = Array.getLength(ary);
    final Object dst = Array.newInstance(ary.getClass().getComponentType(), size);
    System.arraycopy(ary, 0, dst, 0, size);
    return dst;
}

From source file:com.microsoft.tfs.core.internal.db.DBStatement.java

private void setParameters(final PreparedStatement ps, final Object args) throws SQLException {
    if (args == null) {
        return;//from w w w. j a v a 2  s.  com
    }

    if (!args.getClass().isArray()) {
        ps.setObject(1, args);
    } else {
        final int len = Array.getLength(args);
        for (int i = 0; i < len; i++) {
            ps.setObject(i + 1, Array.get(args, i));
        }
    }
}

From source file:adams.ml.Dataset.java

public void setMappingFromDataRow(DataRow dr) {
    for (String key : dr.getKeys()) {
        BaseData bd = dr.get(key);//  w w w.ja  v  a  2 s . c  om
        if (bd != null) {
            if (bd.isNumeric()) {
                setType(key, BaseData.Type.NUMERIC);
            } else if (bd.isArray()) {
                if (Array.getLength(bd.getData()) > 0) {
                    Object ao = Array.get(bd.getData(), 0);
                    if (BaseData.isNumeric(ao)) {
                        setType(key, BaseData.Type.NUMERIC, Array.getLength(bd.getData()));
                    } else {
                        setType(key, BaseData.Type.STRING, Array.getLength(bd.getData()));
                    }
                }
            } else {
                setType(key, BaseData.Type.STRING);
            }
        }
    }
}