Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

In this page you can find the example usage for java.lang Class getDeclaredField.

Prototype

@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Usage

From source file:org.openremote.server.inventory.DiscoveryService.java

protected Adapter createAdapter(String name, String componentType, UriEndpointComponent component,
        Properties componentProperties) {
    LOG.info("Creating adapter for component: " + name);
    Class<? extends Endpoint> endpointClass = component.getEndpointClass();

    String label = componentProperties.containsKey(COMPONENT_LABEL)
            ? componentProperties.get(COMPONENT_LABEL).toString()
            : null;//w w  w  . j av a 2 s  .c o  m

    if (label == null)
        throw new RuntimeException("Component missing label property: " + name);

    String discoveryEndpoint = componentProperties.containsKey(COMPONENT_DISCOVERY_ENDPOINT)
            ? componentProperties.get(COMPONENT_DISCOVERY_ENDPOINT).toString()
            : null;

    Adapter adapter = new Adapter(label, name, componentType, discoveryEndpoint);

    ComponentConfiguration config = component.createComponentConfiguration();
    ObjectNode properties = JSON.createObjectNode();
    for (Map.Entry<String, ParameterConfiguration> configEntry : config.getParameterConfigurationMap()
            .entrySet()) {
        try {
            Field field = endpointClass.getDeclaredField(configEntry.getKey());
            if (field.isAnnotationPresent(UriParam.class)) {
                UriParam uriParam = field.getAnnotation(UriParam.class);

                ObjectNode property = JSON.createObjectNode();

                if (uriParam.label().length() > 0) {
                    property.put("label", uriParam.label());
                }

                if (uriParam.description().length() > 0) {
                    property.put("description", uriParam.description());

                }

                if (uriParam.defaultValue().length() > 0) {
                    property.put("defaultValue", uriParam.defaultValue());
                }

                if (uriParam.defaultValueNote().length() > 0) {
                    property.put("defaultValueNote", uriParam.defaultValueNote());
                }

                if (String.class.isAssignableFrom(field.getType())) {
                    property.put("type", "string");
                } else if (Long.class.isAssignableFrom(field.getType())) {
                    property.put("type", "long");
                } else if (Integer.class.isAssignableFrom(field.getType())) {
                    property.put("type", "integer");
                } else if (Double.class.isAssignableFrom(field.getType())) {
                    property.put("type", "double");
                } else if (Boolean.class.isAssignableFrom(field.getType())) {
                    property.put("type", "boolean");
                } else {
                    throw new RuntimeException(
                            "Unsupported type of adapter endpoint property '" + name + "': " + field.getType());
                }

                if (field.isAnnotationPresent(NotNull.class)) {
                    for (Class<?> group : field.getAnnotation(NotNull.class).groups()) {
                        if (ValidationGroupDiscovery.class.isAssignableFrom(group)) {
                            property.put("required", true);
                            break;
                        }
                    }
                }

                String propertyName = uriParam.name().length() != 0 ? uriParam.name() : field.getName();
                LOG.debug("Adding adapter property '" + propertyName + "': " + property);
                properties.set(propertyName, property);
            }
        } catch (NoSuchFieldException ex) {
            // Ignoring config parameter if there is no annotated field on endpoint class
            // TODO: Inheritance of endpoint classes? Do we care?
        }
    }

    try {
        adapter.setProperties(JSON.writeValueAsString(properties));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    return adapter;
}

From source file:py.una.pol.karaku.reports.DynamicUtils.java

/**
 * Metodo que obtiene la clase de cada detalle que sera incorporado en los
 * reportes del tipo cabecera-detalle.// ww  w  . ja  va2 s  .  c o  m
 * 
 * @param clazz
 *            Clase de la cabecera
 * @param detail
 *            Detalle que se desea agregar al reporte
 * @return Clase del detalle
 * @throws ReportException
 */
private Class<?> getClazzDetail(Class<?> clazz, Detail detail) throws ReportException {

    Class<?> clazzDetail = null;
    try {
        if (detail.getField().contains(".")) {
            clazzDetail = Object.class;
        } else {
            Field field = clazz.getDeclaredField(detail.getField());
            clazzDetail = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
        }
    } catch (NoSuchFieldException e) {
        throw new ReportException(e);
    }
    return clazzDetail;
}

From source file:com.impetus.client.cassandra.query.CassQuery.java

/**
 * Returns bytes value for given value./*from  ww w  . j  a  v  a2 s . c o m*/
 * 
 * @param jpaFieldName
 *            field name.
 * @param m
 *            entity metadata
 * @param value
 *            value.
 * @return bytes value.
 */
ByteBuffer getBytesValue(String jpaFieldName, EntityMetadata m, Object value) {
    Attribute idCol = m.getIdAttribute();
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());

    EntityType entity = metaModel.entity(m.getEntityClazz());
    Field f = null;
    boolean isId = false;
    if (((AbstractAttribute) idCol).getJPAColumnName().equals(jpaFieldName)) {
        f = (Field) idCol.getJavaMember();
        isId = true;
    } else {
        if (jpaFieldName != null && jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) > 0) {
            String embeddedFieldName = jpaFieldName.substring(0,
                    jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER));
            String columnFieldName = jpaFieldName.substring(
                    jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) + 1, jpaFieldName.length());

            Attribute embeddedAttr = entity.getAttribute(embeddedFieldName);
            try {
                Class<?> embeddedClass = embeddedAttr.getJavaType();
                if (Collection.class.isAssignableFrom(embeddedClass)) {
                    Class<?> genericClass = PropertyAccessorHelper
                            .getGenericClass((Field) embeddedAttr.getJavaMember());
                    f = genericClass.getDeclaredField(columnFieldName);
                } else {
                    f = embeddedClass.getDeclaredField(columnFieldName);
                }

            } catch (SecurityException e) {
                log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e);
                throw new QueryHandlerException("Error while extrating " + jpaFieldName + ".");
            } catch (NoSuchFieldException e) {
                log.error("Error while extrating " + jpaFieldName + ", Caused by: ", e);
                throw new QueryHandlerException("Error while extrating " + jpaFieldName + ".");
            }
        } else {
            String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();

            if (!jpaFieldName.equals(discriminatorColumn)) {
                String fieldName = m.getFieldName(jpaFieldName);

                Attribute col = entity.getAttribute(fieldName);
                if (col == null) {
                    throw new QueryHandlerException("column type is null for: " + jpaFieldName);
                }
                f = (Field) col.getJavaMember();
            }
        }
    }

    // need to do integer.parseInt..as value will be string in case of
    // create query.
    if (f != null && f.getType() != null) {
        return CassandraUtilities.toBytes(value, f);
    } else {
        // default is String type
        return CassandraUtilities.toBytes(value, String.class);
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

protected Field findField(Class clazz, String fieldName) {
    if (clazz == null)
        return null;

    try {/*from  w  w w .  ja  va  2  s.  c  o  m*/
        final Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true); // (Field is probably private) 
        return field;
    } catch (NoSuchFieldException ex) {
        // Silently ignore
        return null;
    } catch (Exception ex) { // Example SecurityException
        warn(ex);
        return null;
    }
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

private static boolean isTransientField(String name, Class beanClass) {
    try {/*from  w  w  w. j a v  a2  s.co m*/
        return isTransientField(beanClass.getDeclaredField(name));
    } catch (Exception e) {
        // swallow exception
    }
    return false;
}

From source file:gemlite.core.internal.db.DBSynchronizer.java

/**
 * Get or create a {@link PreparedStatement} for an insert operation.
 *///from w  w w.j a  v  a 2 s .c  om
protected PreparedStatement getExecutableInsertPrepStmntPKBased(AsyncEvent pkEvent, PreparedStatement prevPS)
        throws SQLException {
    final String regionName = pkEvent.getRegion().getName();
    PreparedStatement ps = this.insertStmntMap.get(regionName);

    IMapperTool tool = DomainRegistry.getMapperTool(regionName);
    String tableName = DomainRegistry.regionToTable(regionName);
    List<String> valueFields = tool.getValueFieldNames();

    if (ps == null) {
        final String dmlString = AsyncEventHelper.getInsertString(tableName, valueFields);
        if (logger.isDebugEnabled()) {
            logger.info("DBSynchronizer::getExecutableInsertPrepStmntPKBased: " + "preparing '" + dmlString
                    + "' for event: " + pkEvent);
        }
        ps = conn.prepareStatement(dmlString);
        this.insertStmntMap.put(tableName, ps);
    } else if (prevPS == ps) {
        // add a new batch of values
        ps.addBatch();
    }
    int paramIndex = 1;
    Class valueClass = tool.getValueClass();
    for (int colIdx = 0; colIdx < valueFields.size(); colIdx++) {
        String field = valueFields.get(colIdx);
        try {
            Map map = PropertyUtils.describe(pkEvent.getDeserializedValue());
            Object val = map.get(field);
            String type = valueClass.getDeclaredField(field).getType().getName();
            helper.setColumnInPrepStatement(type, val, ps, this, paramIndex);
        } catch (Exception e) {
            throw new SQLException(e);
        }
        paramIndex++;
    }
    return ps;
}

From source file:gemlite.core.internal.db.DBSynchronizer.java

/**
 * Get or create a {@link PreparedStatement} for a primary key based update
 * operation.//  w  w w. java2  s.  c  om
 */
protected PreparedStatement getExecutableUpdatePrepStmntPKBased(AsyncEvent pkEvent, PreparedStatement prevPS)
        throws SQLException {
    final String regionName = pkEvent.getRegion().getName();
    IMapperTool tool = DomainRegistry.getMapperTool(regionName);
    String tableName = DomainRegistry.regionToTable(regionName);
    List<String> valueFields = tool.getValueFieldNames();

    final int numUpdatedCols = valueFields.size();
    StringBuilder searchKeyBuff = new StringBuilder(tableName);
    int paramIndex;
    for (paramIndex = 0; paramIndex < numUpdatedCols; paramIndex++) {
        searchKeyBuff.append('_');
        searchKeyBuff.append(valueFields.get(paramIndex));
    }
    String searchKey = searchKeyBuff.toString();
    final Object pkValues = pkEvent.getDeserializedValue();
    final List<String> keyFields = tool.getKeyFieldNames();
    PreparedStatement ps = this.updtStmntMap.get(searchKey);
    if (ps == null) {
        final String dmlString = AsyncEventHelper.getUpdateString(tableName, keyFields, valueFields);
        if (logger.isDebugEnabled()) {
            logger.info("DBSynchronizer::getExecutableInsertPrepStmntPKBased: " + "preparing '" + dmlString
                    + "' for event: " + pkEvent);
        }
        ps = conn.prepareStatement(dmlString);
        this.updtStmntMap.put(searchKey, ps);
    } else if (prevPS == ps) {
        // add a new batch of values
        ps.addBatch();
    }
    // Set updated col values
    Class valueClass = tool.getValueClass();
    Class keyClass = tool.getKeyClass();
    for (paramIndex = 1; paramIndex <= numUpdatedCols; paramIndex++) {
        String field = valueFields.get(paramIndex - 1);
        try {
            Map map = PropertyUtils.describe(pkEvent.getDeserializedValue());
            Object val = map.get(field);
            String type = valueClass.getDeclaredField(field).getType().getName();
            helper.setColumnInPrepStatement(type, val, ps, this, paramIndex);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }
    // Now set the Pk values
    setKeysInPrepStatement(pkValues, keyFields, valueClass, ps, paramIndex);
    return ps;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

private MongoClient client() {
    mutex.lock();//from   w ww  .j av a2 s  .c  o  m
    try {
        if (__client == null) {
            final MongoClientOptions options = MongoClientOptions.builder()
                    .readPreference(ReadPreference.nearest()).writeConcern(WriteConcern.ACKNOWLEDGED).build();
            final Splitter splitter = on(':').trimResults().omitEmptyStrings().limit(2);
            final List<ServerAddress> seeds = from(CONFIG_MANAGER.getDbHosts())
                    .transform(new Function<String, ServerAddress>() {
                        @Override
                        public ServerAddress apply(final String entry) {
                            ServerAddress seed = null;
                            try {
                                final List<String> tokens = splitter.splitToList(entry);
                                switch (tokens.size()) {
                                case 1:
                                    seed = new ServerAddress(tokens.get(0), 27017);
                                    break;
                                case 2:
                                    int port = parseInt(tokens.get(1));
                                    seed = new ServerAddress(tokens.get(0), port);
                                    break;
                                default:
                                    break;
                                }
                            } catch (Exception e) {
                                LOGGER.error("Invalid host", e);
                            }
                            return seed;
                        }
                    }).filter(notNull()).toList();
            // enable/disable authentication (requires MongoDB server to be configured to support authentication)
            final List<MongoCredential> credentials = newArrayList();
            if (!CONFIG_MANAGER.isAnonymousDbAccess()) {
                credentials.add(createMongoCRCredential(CONFIG_MANAGER.getDbUsername(),
                        CONFIG_MANAGER.getDbName(), CONFIG_MANAGER.getDbPassword().toCharArray()));
            }
            __client = new MongoClient(seeds, credentials, options);
            // check class attributes accessed by reflection
            try {
                final Field metadataField = BaseFile.class.getDeclaredField(METADATA_ATTR);
                checkNotNull(metadataField, "Metadata property (" + METADATA_ATTR + ") not found in file base: "
                        + BaseFile.class.getCanonicalName());
                final Class<?> metadataType = metadataField.getType();
                checkState(Versionable.class.isAssignableFrom(metadataType),
                        "Metadata does not implements versionable: " + metadataType.getCanonicalName());
                checkNotNull(Versionable.class.getDeclaredField(IS_LATEST_VERSION_ATTR),
                        "Version property (" + IS_LATEST_VERSION_ATTR + ") not found in versionable: "
                                + Versionable.class.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_LINK_ATTR),
                        "Open access link property (" + OPEN_ACCESS_LINK_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_DATE_ATTR),
                        "Open access date property (" + OPEN_ACCESS_DATE_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Object versioning needs a compatible version of the LVL core library, but none is available",
                        e);
            }
        }
        return __client;
    } finally {
        mutex.unlock();
    }
}

From source file:net.sf.json.JSONObject.java

private static boolean isTransientField(String name, Class beanClass, JsonConfig jsonConfig) {
    try {/*w w w . j  av a  2s  .co m*/
        Field field = beanClass.getDeclaredField(name);
        if ((field.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT)
            return true;
        return isTransient(field, jsonConfig);
    } catch (Exception e) {
        log.info("Error while inspecting field " + beanClass + "." + name + " for transient status.", e);
    }
    return false;
}

From source file:com.canappi.connector.yp.yhere.SearchView.java

public void viewDidLoad() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        Set<String> keys = extras.keySet();
        for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
            String key = iter.next();
            Class c = SearchView.class;
            try {
                Field f = c.getDeclaredField(key);
                Object extra = extras.get(key);
                String value = extra.toString();
                f.set(this, value);
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from   w ww  . j a  v a2 s  .  c o m
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {

    }

    searchViewIds = new HashMap();
    searchViewValues = new HashMap();

    isUserDefault = false;

    resultsListView = (ListView) findViewById(R.id.resultsTable);
    resultsAdapter = new ResultsEfficientAdapter(this);

    businessNameArray = new ArrayList<String>();

    latitudeArray = new ArrayList<String>();

    longitudeArray = new ArrayList<String>();

    listingIdArray = new ArrayList<String>();

    phoneArray = new ArrayList<String>();

    callArray = new ArrayList<String>();

    streetArray = new ArrayList<String>();

    cityArray = new ArrayList<String>();
    resultsListView.setAdapter(resultsAdapter);
    didSelectViewController();

}