Example usage for java.lang.reflect Field set

List of usage examples for java.lang.reflect Field set

Introduction

In this page you can find the example usage for java.lang.reflect Field set.

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:edu.stanford.muse.webapp.Accounts.java

/** does account setup and login (and look up default folder if well-known account) from the given request.
 * request params are loginName<N>, password<N>, etc (see loginForm for details).
 * returns an object with {status: 0} if success, or {status: <non-zero>, errorMessage: '... '} if failure.
 * if success and account has a well-known sent mail folder, the returned object also has something like: 
 * {defaultFolder: '[Gmail]/Sent Mail', defaultFolderCount: 1033}
 * accounts on the login page are numbered 0 upwards. */
public static JSONObject login(HttpServletRequest request, int accountNum) throws IOException, JSONException {
    JSONObject result = new JSONObject();

    HttpSession session = request.getSession();
    // allocate the fetcher if it doesn't already exist
    MuseEmailFetcher m = null;//from ww  w .  j a  v  a 2s  .  co m
    synchronized (session) // synchronize, otherwise may lose the fetcher when multiple accounts are specified and are logged in to simult.
    {
        m = (MuseEmailFetcher) JSPHelper.getSessionAttribute(session, "museEmailFetcher");
        boolean doIncremental = request.getParameter("incremental") != null;

        if (m == null || !doIncremental) {
            m = new MuseEmailFetcher();
            session.setAttribute("museEmailFetcher", m);
        }
    }

    // note: the same params get posted with every accountNum
    // we'll update for all account nums, because sometimes account #0 may not be used, only #1 onwards. This should be harmless.
    // we used to do only altemailaddrs, but now also include the name.
    updateUserInfo(request);

    String accountType = request.getParameter("accountType" + accountNum);
    if (Util.nullOrEmpty(accountType)) {
        result.put("status", 1);
        result.put("errorMessage", "No information for account #" + accountNum);
        return result;
    }

    String loginName = request.getParameter("loginName" + accountNum);
    String password = request.getParameter("password" + accountNum);
    String protocol = request.getParameter("protocol" + accountNum);
    //   String port = request.getParameter("protocol" + accountNum);  // we don't support pop/imap on custom ports currently. can support server.com:port syntax some day
    String server = request.getParameter("server" + accountNum);
    String defaultFolder = request.getParameter("defaultFolder" + accountNum);

    if (server != null)
        server = server.trim();

    if (loginName != null)
        loginName = loginName.trim();

    // for these ESPs, the user may have typed in the whole address or just his/her login name
    if (accountType.equals("gmail") && loginName.indexOf("@") < 0)
        loginName = loginName + "@gmail.com";
    if (accountType.equals("yahoo") && loginName.indexOf("@") < 0)
        loginName = loginName + "@yahoo.com";
    if (accountType.equals("live") && loginName.indexOf("@") < 0)
        loginName = loginName + "@live.com";
    if (accountType.equals("stanford") && loginName.indexOf("@") < 0)
        loginName = loginName + "@stanford.edu";
    if (accountType.equals("gmail"))
        server = "imap.gmail.com";

    // add imapdb stuff here.
    boolean imapDBLookupFailed = false;
    String errorMessage = "";
    int errorStatus = 0;

    if (accountType.equals("email") && Util.nullOrEmpty(server)) {
        log.info("accountType = email");

        defaultFolder = "Sent";

        {
            // ISPDB from Mozilla
            imapDBLookupFailed = true;

            String emailDomain = loginName.substring(loginName.indexOf("@") + 1);
            log.info("Domain: " + emailDomain);

            // from http://suhothayan.blogspot.in/2012/05/how-to-install-java-cryptography.html
            // to get around the need for installingthe unlimited strength encryption policy files.
            try {
                Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
                field.setAccessible(true);
                field.set(null, java.lang.Boolean.FALSE);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            //            URL url = new URL("https://live.mozillamessaging.com/autoconfig/v1.1/" + emailDomain);
            URL url = new URL("https://autoconfig.thunderbird.net/v1.1/" + emailDomain);
            try {
                URLConnection urlConnection = url.openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(in);

                NodeList configList = doc.getElementsByTagName("incomingServer");
                log.info("configList.getLength(): " + configList.getLength());

                int i;
                for (i = 0; i < configList.getLength(); i++) {
                    Node config = configList.item(i);
                    NamedNodeMap attributes = config.getAttributes();
                    if (attributes.getNamedItem("type").getNodeValue().equals("imap")) {
                        log.info("[" + i + "] type: " + attributes.getNamedItem("type").getNodeValue());
                        Node param = config.getFirstChild();
                        String nodeName, nodeValue;
                        String paramHostName = "";
                        String paramUserName = "";
                        do {
                            if (param.getNodeType() == Node.ELEMENT_NODE) {
                                nodeName = param.getNodeName();
                                nodeValue = param.getTextContent();
                                log.info(nodeName + "=" + nodeValue);
                                if (nodeName.equals("hostname")) {
                                    paramHostName = nodeValue;
                                } else if (nodeName.equals("username")) {
                                    paramUserName = nodeValue;
                                }
                            }
                            param = param.getNextSibling();
                        } while (param != null);

                        log.info("paramHostName = " + paramHostName);
                        log.info("paramUserName = " + paramUserName);

                        server = paramHostName;
                        imapDBLookupFailed = false;
                        if (paramUserName.equals("%EMAILADDRESS%")) {
                            // Nothing to do with loginName
                        } else if (paramUserName.equals("%EMAILLOCALPART%")
                                || paramUserName.equals("%USERNAME%")) {
                            // Cut only local part
                            loginName = loginName.substring(0, loginName.indexOf('@') - 1);
                        } else {
                            imapDBLookupFailed = true;
                            errorMessage = "Invalid auto configuration";
                        }

                        break; // break after find first IMAP host name
                    }
                }
            } catch (Exception e) {
                Util.print_exception("Exception trying to read ISPDB", e, log);
                errorStatus = 2; // status code = 2 => ispdb lookup failed
                errorMessage = "No automatic configuration available for " + emailDomain
                        + ", please use the option to provide a private (IMAP) server. \nDetails: "
                        + e.getMessage()
                        + ". \nRunning with java -Djavax.net.debug=all may provide more details.";
            }
        }
    }

    if (imapDBLookupFailed) {
        log.info("ISPDB Fail");
        result.put("status", errorStatus);
        result.put("errorMessage", errorMessage);
        // add other fields here if needed such as server name attempted to be looked up in case the front end wants to give a message to the user
        return result;
    }

    boolean isServerAccount = accountType.equals("gmail") || accountType.equals("email")
            || accountType.equals("yahoo") || accountType.equals("live") || accountType.equals("stanford")
            || accountType.equals("gapps") || accountType.equals("imap") || accountType.equals("pop")
            || accountType.startsWith("Thunderbird");

    if (isServerAccount) {
        boolean sentOnly = "on".equals(request.getParameter("sent-messages-only"));
        return m.addServerAccount(server, protocol, defaultFolder, loginName, password, sentOnly);
    } else if (accountType.equals("mbox") || accountType.equals("tbirdLocalFolders")) {
        try {
            String mboxDir = request.getParameter("mboxDir" + accountNum);
            String emailSource = request.getParameter("emailSource" + accountNum);
            // for non-std local folders dir, tbird prefs.js has a line like: user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb");
            log.info("adding mbox account: " + mboxDir);
            errorMessage = m.addMboxAccount(emailSource, mboxDir, accountType.equals("tbirdLocalFolders"));
            if (!Util.nullOrEmpty(errorMessage)) {
                result.put("errorMessage", errorMessage);
                result.put("status", 1);
            } else
                result.put("status", 0);
        } catch (MboxFolderNotReadableException e) {
            result.put("errorMessage", e.getMessage());
            result.put("status", 1);
        }
    } else {
        result.put("errorMessage", "Sorry, unknown account type: " + accountType);
        result.put("status", 1);
    }
    return result;
}

From source file:jp.terasoluna.fw.beans.jxpath.JXPATH152PatchActivator.java

/**
 * ??//from   w ww .  j a  v a2s.co m
 */
private static void activate() {
    try {
        // ?????Map?
        Field byClassField = JXPathIntrospector.class.getDeclaredField("byClass");
        byClassField.setAccessible(true);
        Map<?, ?> byClass = (Map<?, ?>) byClassField.get(null);

        Field byInterfaceField = JXPathIntrospector.class.getDeclaredField("byInterface");
        byInterfaceField.setAccessible(true);
        Map<?, ?> byInterface = (Map<?, ?>) byInterfaceField.get(null);

        // Map??
        byClassField.set(null, new HashMapForJXPathIntrospector<Object, Object>(byClass));
        byInterfaceField.set(null, new HashMapForJXPathIntrospector<Object, Object>(byInterface));

        log.info("JXPATH-152 Patch activation succeeded.");
    } catch (Exception e) {
        // ?????
        // ???????commons-JXPath?????
        log.fatal("JXPATH-152 Patch activation failed.", e);
    }
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * Check each field in object to see if it is already seen. This will modify
 * collections, lists and arrays as well as the fields in an object.
 * /* w  w w . j  a v  a  2 s .c o m*/
 * @param obj
 *            the object to be checked for duplicates.
 * @param seen
 *            objects that have already been checked.
 * @return the object with all duplicates removed
 */
private static <T> T removeDuplicate(T obj, Map<String, Object> seen) {
    if (obj == null) {
        return null;
    }
    if (obj instanceof AbstractBean) {
        String id = ((AbstractBean) obj).getId();
        if (seen.containsKey(id)) {
            return (T) seen.get(id);
        }
        seen.put(id, obj);

        // check all subfields
        for (Field field : obj.getClass().getDeclaredFields()) {
            if ((field.getModifiers() & Modifier.FINAL) == 0) {
                try {
                    field.setAccessible(true);
                    field.set(obj, removeDuplicate(field.get(obj), seen));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } else if (obj instanceof Collection<?>) {
        Collection col = (Collection) obj;
        ArrayList arr = new ArrayList(col);
        col.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object x = removeDuplicate(arr.get(i), seen);
            col.add(x);
        }
    } else if (obj instanceof Map<?, ?>) {
        Map map = (Map) obj;
        ArrayList<Entry> arr = new ArrayList(map.entrySet());
        map.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object k = removeDuplicate(arr.get(i).getKey(), seen);
            Object v = removeDuplicate(arr.get(i).getValue(), seen);
            map.put(k, v);
        }
    } else if (obj.getClass().isArray()) {
        Object[] arr = (Object[]) obj;
        for (int i = 0; i < arr.length; i++) {
            arr[i] = removeDuplicate(arr[i], seen);
        }
    }

    return obj;
}

From source file:com.vanstone.common.util.ReflectionUtils.java

/**
 * , private/protected, ??setter./*  w w w . j  av a  2  s  .co m*/
 */
public static void setFieldValue(final Object object, final String fieldName, final Object value) {
    Field field = getDeclaredField(object, fieldName);

    if (field == null) {
        throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + object + "]");
    }

    makeAccessible(field);

    try {
        field.set(object, value);
    } catch (IllegalAccessException e) {
        LOG.error("??:{}" + e.getMessage());
    }
}

From source file:com.ghy.common.util.reflection.ReflectionUtils.java

/**
 * value String/*  w  w  w .  ja  v  a  2s.c  om*/
 * , private/protected, ??setter.
 */
public static void setFieldsValues(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        return;
    }

    try {
        Class<?> type = field.getType();
        if (type.equals(Integer.class) || type.equals(int.class)) {
            field.set(obj, Integer.valueOf((String) value));
        } else if (type.equals(Long.class) || type.equals(long.class)) {
            field.set(obj, Long.valueOf((String) value));
        } else if (type.equals(Double.class) || type.equals(double.class)) {
            field.set(obj, Double.valueOf((String) value));
        } else if (type.equals(Float.class) || type.equals(float.class)) {
            field.set(obj, Float.valueOf((String) value));
        } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
            field.set(obj, Boolean.valueOf((String) value));
        } else if (type.equals(Date.class)) {
            field.set(obj, new SimpleDateFormat("yyyyMMddHHmmsssss").parse((String) value));
        } else {
            field.set(obj, value);
        }
    } catch (IllegalAccessException e) {
        logger.error(":{}", e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error(":{}", e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        logger.error(":{}", e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Read a parsed value//from  ww w . j  ava2s  . com
 *
 * @throws IllegalAccessException
 */
private static void annotate(Field field, String type, String name, Object annotated)
        throws IllegalAccessException {

    if (name.equals("null"))
        name = field.getName();

    field.set(annotated, values.get(type).get(name));

}

From source file:Main.java

private static boolean setProxyPreICS(WebView webView, String host, final int port) {
    HttpHost proxyServer;/*ww w  . j  a va 2s.c  o  m*/
    if (null == host) {
        proxyServer = null;
    } else {
        proxyServer = new HttpHost(host, port);
    }
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webView.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:com.belle.infrastructure.util.ReflectionUtils.java

/**
 * , private/protected, ??setter.// www .j  a v a2s .com
 */
public static void setFieldValue(final Object object, final String fieldName, final Object value) {
    Field field = getDeclaredField(object, fieldName);

    if (field == null) {
        throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + object + "]");
    }

    makeAccessible(field);

    try {
        field.set(object, value);
    } catch (IllegalAccessException e) {
        logger.error("??:{}", e);
    }
}

From source file:com.microsoft.Malmo.Utils.TextureHelper.java

public static void hookIntoRenderPipeline() {
    // Subvert the render manager. This MUST be called at the right time (FMLInitializationEvent).
    // 1: Replace the MC entity renderer with our own:
    Minecraft.getMinecraft().entityRenderer = new MalmoEntityRenderer(Minecraft.getMinecraft(),
            Minecraft.getMinecraft().getResourceManager());
    // 2: Create a new RenderManager:
    RenderManager newRenderManager = new TextureHelper.MalmoRenderManager(Minecraft.getMinecraft().renderEngine,
            Minecraft.getMinecraft().getRenderItem());
    // 3: Use reflection to:
    //      a) replace Minecraft's RenderManager with our new RenderManager
    //      b) point Minecraft's RenderGlobal object to the new RenderManager

    // Are we in the dev environment or deployed?
    boolean devEnv = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");
    // We need to know, because the names will either be obfuscated or not.
    String mcRenderManagerName = devEnv ? "renderManager" : "field_175616_W";
    String globalRenderManagerName = devEnv ? "renderManager" : "field_175010_j";
    // NOTE: obfuscated name may need updating if Forge changes - search in
    // ~\.gradle\caches\minecraft\de\oceanlabs\mcp\mcp_snapshot\20161220\1.11.2\srgs\mcp-srg.srg
    Field renderMan;
    Field globalRenderMan;//from   w w  w  .ja  v a 2s  .com
    try {
        renderMan = Minecraft.class.getDeclaredField(mcRenderManagerName);
        renderMan.setAccessible(true);
        renderMan.set(Minecraft.getMinecraft(), newRenderManager);

        globalRenderMan = RenderGlobal.class.getDeclaredField(globalRenderManagerName);
        globalRenderMan.setAccessible(true);
        globalRenderMan.set(Minecraft.getMinecraft().renderGlobal, newRenderManager);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Create and AudioInputStream and update the field
 *
 * @throws IllegalAccessException//  www . j  ava  2 s.c  om
 */
private static void annotateAudio(Field field, Audio annotation, Object annotated)
        throws IllegalAccessException {
    try {
        String res = getPath(annotation.value(), AUDIO_DIR);
        field.set(annotated, AudioSystem.getAudioInputStream(new File(res)));
    } catch (IOException | UnsupportedAudioFileException e) {
        e.printStackTrace();
    }
}