Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.hisp.dhis.webwork.configuration.UrlXmlConfigurationProvider.java

protected void addResultTypes(PackageConfig packageContext, Element element) {
    NodeList resultTypeList = element.getElementsByTagName("result-type");

    for (int i = 0; i < resultTypeList.getLength(); i++) {
        Element resultTypeElement = (Element) resultTypeList.item(i);
        String name = resultTypeElement.getAttribute("name");
        String className = resultTypeElement.getAttribute("class");
        String def = resultTypeElement.getAttribute("default");

        Location loc = DomHelper.getLocationObject(resultTypeElement);

        Class clazz = verifyResultType(className, loc);
        if (clazz != null) {
            String paramName = null;
            try {
                paramName = (String) clazz.getField("DEFAULT_PARAM").get(null);
            } catch (Throwable t) {
                // if we get here, the result type doesn't have a default
                // param defined.
            }// w w  w  .j a  va  2s . co  m
            ResultTypeConfig resultType = new ResultTypeConfig(name, className, paramName);
            resultType.setLocation(DomHelper.getLocationObject(resultTypeElement));

            Map params = XmlHelper.getParams(resultTypeElement);

            if (!params.isEmpty()) {
                resultType.setParams(params);
            }
            packageContext.addResultTypeConfig(resultType);

            // set the default result type
            if ("true".equals(def)) {
                packageContext.setDefaultResultType(name);
            }
        }
    }
}

From source file:com.csipsimple.service.DownloadLibService.java

private boolean isCompatibleStack(JSONObject filter) throws SecurityException, NoSuchFieldException,
        ClassNotFoundException, IllegalArgumentException, IllegalAccessException, JSONException {

    //For each filter keys, we check if the filter is not invalid
    Iterator<?> iter = filter.keys();
    while (iter.hasNext()) {
        //Each filter key correspond to a android class which values has to be checked
        String class_filter = (String) iter.next();
        //Get this class
        Class<?> cls = Class.forName(class_filter);

        //Then for this class, we have to check if each static field matches defined regexp rule
        Iterator<?> cls_iter = filter.getJSONObject(class_filter).keys();

        while (cls_iter.hasNext()) {
            String field_name = (String) cls_iter.next();
            Field field = cls.getField(field_name);
            //Get the current value on the system
            String current_value = field.get(null).toString();
            //Get the filter for this value
            String regexp_filter = filter.getJSONObject(class_filter).getString(field_name);

            //Check if matches
            if (!Pattern.matches(regexp_filter, current_value)) {
                Log.d(THIS_FILE, "Regexp not match : " + current_value + " matches /" + regexp_filter + "/");
                return false;
            }/*from   w  w w .  j a  v  a  2  s .  c o  m*/
        }
    }
    return true;
}

From source file:org.hippoecm.repository.LoggingServlet.java

/**
 * Set the logger's log level through reflection
 * @param name String the name of the logger to change
 * @param level String the new log level
 *//*from  ww  w  . ja v a 2s.c  o m*/
private void setLoggerLevel(String name, String level) {
    if (name == null || name.length() == 0) {
        log.warn("Invalid empty name. Not settting log level");
        return;
    }

    if (isJDK14Log) {
        java.util.logging.LogManager logManager = java.util.logging.LogManager.getLogManager();
        java.util.logging.Logger logger = logManager.getLogger(name);

        if (logger != null) {
            logger.setLevel(Level.parse(level));
        } else {
            log.warn("Logger not found : " + name);
        }
    } else if (isLog4jLog) {
        try {
            log.warn("Setting logger " + name + " to level " + level);

            // basic log4j reflection
            Class<?> loggerClass = Class.forName("org.apache.log4j.Logger");
            Class<?> levelClass = Class.forName("org.apache.log4j.Level");
            Class<?> logManagerClass = Class.forName("org.apache.log4j.LogManager");
            Method setLevel = loggerClass.getMethod("setLevel", levelClass);

            // get the logger
            Object logger = logManagerClass.getMethod("getLogger", String.class).invoke(null, name);

            // get the static level object field, e.g. Level.INFO
            Field levelField;
            levelField = levelClass.getField(level);
            Object levelObj = levelField.get(null);

            // set the level
            setLevel.invoke(logger, levelObj);
        } catch (NoSuchFieldException e) {
            log.warn("Unable to find Level." + level + " , not adjusting logger " + name);
        } catch (Exception e) {
            log.error("Unable to set logger " + name + " + to level " + level, e);
        }
    } else {
        log.warn("Unable to determine logger");
    }
}

From source file:org.musicrecital.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified scope 
 * @return int//  w  ww.  java 2 s.  c  o m
 * @throws JspException if processing fails
 */
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                Object value = c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:cn.com.sinosoft.util.exception.ExceptionUtils.java

/**
 * <p>//from   w  ww.  j  a  va  2 s.  c o m
 * Checks whether this <code>Throwable</code> class can store a cause.
 * </p>
 * 
 * <p>
 * This method does <b>not</b> check whether it actually does store a cause.
 * <p>
 * 
 * @param throwable
 *            the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class cls = throwable.getClass();
    synchronized (CAUSE_METHOD_NAMES_LOCK) {
        for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
            try {

                Class<?>[] parameterTypes = {};
                Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], parameterTypes);
                if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                    return true;
                }
            } catch (NoSuchMethodException ignored) {
                // exception ignored
            } catch (SecurityException ignored) {
                // exception ignored
            }
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
        // exception ignored
    } catch (SecurityException ignored) {
        // exception ignored
    }

    return false;
}

From source file:net.facework.core.http.TinyHttpServer.java

@Override
public void onCreate() {

    super.onCreate();

    mContext = getApplicationContext();/* w  ww .j a  v  a 2s.  c  o  m*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Let's restore the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(mHttpPortKey, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(mHttpsPortKey, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(mHttpEnabledKey, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(mHttpsEnabledKey, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:org.openhie.openempi.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified scope 
 * @return int//from   ww w  . j  a  va  2s  .c  o  m
 * @throws JspException if processing fails
 */
@SuppressWarnings("unchecked")
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                Object value = c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:com.gisgraphy.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified scope
 * /* ww  w. jav  a  2 s.c  o  m*/
 * @return int
 * @throws JspException
 *                 if processing fails
 */
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class<?> c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                Object value = c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:com.baqr.baqrcam.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();/*  ww  w .  j a v a2 s  .com*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:com.wifi.brainbreaker.mydemo.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();/*w  w w .  j  a  v a  2 s .c o m*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}