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:se.vgregion.userassociations.hook.UserCommunityActionTest.java

@Before
public void setUp() throws Exception {
    GroupLocalService groupLocalService = mock(GroupLocalService.class);
    Group extern = mock(Group.class);
    Group vgr = mock(Group.class);
    when(groupLocalService.getGroup(anyLong(), eq("VGRegion"))).thenReturn(vgr);
    when(vgr.getGroupId()).thenReturn(1l);
    when(groupLocalService.getGroup(anyLong(), eq("Extern"))).thenReturn(extern);
    when(extern.getGroupId()).thenReturn(2l);

    Field service = GroupLocalServiceUtil.class.getDeclaredField("_service");
    service.setAccessible(true);// w w w .j a va 2 s  .  co m
    service.set(null, groupLocalService);
    //new GroupLocalServiceUtil().setService(groupLocalService);

    PropsUtil.setProps(mock(Props.class));
}

From source file:info.guardianproject.netcipher.web.WebkitProxy.java

/**
 * Set Proxy for Android 3.2 and below./*from w w  w  .  j  a v a 2 s . co  m*/
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(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(TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(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(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(TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:de.fiz.akubra.hdfs.HDFSBlobStoreConnectionTest.java

private HDFSBlobStoreConnection createTestConnection() throws Exception {
    HDFSBlobStoreConnection connection = new HDFSBlobStoreConnection(mockStore);
    Field f = HDFSBlobStoreConnection.class.getDeclaredField("hdfs");
    f.setAccessible(true);/*from   www . jav a 2s .c  o  m*/
    f.set(connection, mockFs);
    return connection;
}

From source file:de.thkwalter.et.schlupfbezifferung.BetriebspunktTest.java

/**
 * Test der Methode {@link Betriebspunkt#getS()}.
 * /*from w w  w.j  av a 2 s  .co  m*/
 * @throws SecurityException 
 * @throws NoSuchFieldException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test
public void testGetS()
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    // Der in diesem Test verwendete Schlupf wird im Prfling gespeichert.
    Field sFeld = Betriebspunkt.class.getDeclaredField("s");
    sFeld.setAccessible(true);
    sFeld.set(this.betriebspunkt, new Double(0.1));

    // Es wird berprft, ob der Schlupf korrekt zurckgegeben wird.
    assertEquals(0.1, this.betriebspunkt.getS(), 0.0);
}

From source file:org.eclipse.gemini.blueprint.test.parsing.DifferentParentsInDifferentBundlesTest.java

private Manifest getParsedManifestFor(CaseWithVisibleMethodsBaseTest testCase) throws Exception {

    System.out.println(ObjectUtils.nullSafeToString(testCase.getBundleContentPattern()));
    Field jarSettings = AbstractConfigurableBundleCreatorTests.class.getDeclaredField("jarSettings");
    // initialize settings
    jarSettings.setAccessible(true);//from   ww  w . j  a v  a 2s.  co m
    jarSettings.set(null, testCase.getSettings());

    Manifest mf = testCase.getManifest();

    return mf;
}

From source file:be.fgov.kszbcss.rhq.websphere.WebSpherePluginLifecycleListener.java

public void shutdown() {
    try {//from ww  w.j a va  2  s.  c o  m
        configManager.removeSSLConfigFromMap(SSL_CONFIG_ALIAS, sslConfig);
    } catch (Exception ex) {
        log.error("Unable to remove SSL configuration", ex);
    }
    System.getProperties().remove("com.ibm.CORBA.ConfigURL");
    System.getProperties().remove("com.ibm.ssl.defaultAlias");
    ConfigQueryServiceFactory.destroy();
    TrustStoreManager.destroy();
    configManager = null;
    sslConfig = null;
    Security.removeProvider(CustomProvider.NAME);

    // Shut down the ORB to prevent class loader leaks and to avoid reconnection
    // issues if the plugin is restarted later.
    log.info("Shutting down ORB");
    orb.shutdown(false);
    orb = null;
    // Also reset the ORB singleton holder; otherwise we will have an issue if the
    // plugin is restarted later (and the GlobalORBFactory class is loaded from the
    // system class loader).
    synchronized (GlobalORBFactory.class) {
        try {
            Field orbField = GlobalORBFactory.class.getDeclaredField("orb");
            orbField.setAccessible(true);
            orbField.set(null, null);
        } catch (Exception ex) {
            log.error(
                    "Failed to remove singleton ORB instance; this will cause a failure to restart the plugin",
                    ex);
        }
    }
}

From source file:com.okta.scim.SingleUserController.java

/**
 * Update via Patch {@link User} attributes
 *
 * @param payload Payload from HTTP request
 * @param id {@link User#id}/*from   ww w. j a  va 2s.c om*/
 *
 * @return {@link #scimError(String, Optional)} / JSON {@link Map} of {@link User}
 */
@RequestMapping(method = RequestMethod.PATCH)
public @ResponseBody Map singleUserPatch(@RequestBody Map<String, Object> payload, @PathVariable String id) {
    List schema = (List) payload.get("schemas");
    List<Map> operations = (List) payload.get("Operations");

    if (schema == null) {
        return scimError("Payload must contain schema attribute.", Optional.of(400));
    }
    if (operations == null) {
        return scimError("Payload must contain operations attribute.", Optional.of(400));
    }

    //Verify schema
    String schemaPatchOp = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
    if (!schema.contains(schemaPatchOp)) {
        return scimError("The 'schemas' type in this request is not supported.", Optional.of(501));
    }

    //Find user for update
    User user = db.findById(id).get(0);

    for (Map map : operations) {
        if (map.get("op") == null && !map.get("op").equals("replace")) {
            continue;
        }
        Map<String, Object> value = (Map) map.get("value");

        // Use Java reflection to find and set User attribute
        if (value != null) {
            for (Map.Entry key : value.entrySet()) {
                try {
                    Field field = user.getClass().getDeclaredField(key.getKey().toString());
                    field.set(user, key.getValue());
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    // Error - Do not update field
                }
            }
        }
    }
    return user.toScimResource();
}

From source file:com.nova.geracao.portfolio.BlogServlet.java

private Object getInstanceFromPropertiesMap(Entity entity, Class<?> klass) {
    Object result = null;/* www  .ja  v  a 2 s  . c  o  m*/
    try {
        Field[] fields = klass.getDeclaredFields();
        result = klass.newInstance();
        for (int i = 0; i < fields.length; i++) {
            if (entity.hasProperty(fields[i].getName())) {
                fields[i].setAccessible(true);
                Object value = entity.getProperty(fields[i].getName());
                if (!ClassUtils.isAssignable(fields[i].getType(), BaseDataClass.class)) {
                    fields[i].set(result, value);
                } else {
                    Object embedValue = getInstanceFromPropertiesMap((EmbeddedEntity) value,
                            fields[i].getType());
                    fields[i].set(result, embedValue);
                }
            }
        }

        Field fieldId = klass.getDeclaredField("id");
        fieldId.setAccessible(true);
        fieldId.set(result, entity.getKey().getId());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.nova.geracao.portfolio.BlogServlet.java

private Object getInstanceFromPropertiesMap(EmbeddedEntity entity, Class<?> klass) {
    Object result = null;//from   ww w . j  a  va  2s . co m
    try {
        Field[] fields = klass.getDeclaredFields();
        result = klass.newInstance();
        for (int i = 0; i < fields.length; i++) {
            if (entity.hasProperty(fields[i].getName())) {
                fields[i].setAccessible(true);
                Object value = entity.getProperty(fields[i].getName());
                if (!ClassUtils.isAssignable(fields[i].getType(), BaseDataClass.class)) {
                    fields[i].set(result, value);
                } else {
                    Object embedValue = getInstanceFromPropertiesMap((EmbeddedEntity) value,
                            fields[i].getType());
                    fields[i].set(result, embedValue);
                }
            }
        }

        Field fieldId = klass.getDeclaredField("id");
        fieldId.setAccessible(true);
        fieldId.set(result, entity.getKey().getId());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.o3project.ocnrm.rest.RMNodeRestApiTest.java

/**
 * Test method for/*from w  ww . j a  v a2  s . co  m*/
 * {@link org.o3project.ocnrm.rest.RMNodeRestApi#createNodeInfo()}
 */
@Test
public void testCreateNodeInfoWithUpperInfo() throws Exception {
    String uppertestData = "{\"upper\":" + "{\"node\":" + "[" + "{\"nodeId\":\"NE=FW1\"},"
            + "{\"nodeId\":\"NE=FW2\"}," + "{\"nodeId\":\"NE=FW3\"}" + "]," + "\"port\":" + "["
            + "{\"portId\":\"NE=FW1, Layer=OCh, TTP=1\"}," + "{\"portId\":\"NE=FW1, Layer=OCh, TTP=2\"},"
            + "{\"portId\":\"NE=FW1, Layer=OCh, CTP=1\"}," + "{\"portId\":\"NE=FW1, Layer=OCh, CTP=2\"},"
            + "{\"portId\":\"NE=FW2, Layer=OCh, TTP=1\"}," + "{\"portId\":\"NE=FW2, Layer=OCh, TTP=2\"},"
            + "{\"portId\":\"NE=FW2, Layer=OCh, CTP=1\"}," + "{\"portId\":\"NE=FW2, Layer=OCh, CTP=2\"},"
            + "{\"portId\":\"NE=FW2, Layer=OCh, CTP=3\"}," + "{\"portId\":\"NE=FW2, Layer=OCh, CTP=4\"},"
            + "{\"portId\":\"NE=FW3, Layer=OCh, TTP=1\"}," + "{\"portId\":\"NE=FW3, Layer=OCh, TTP=2\"},"
            + "{\"portId\":\"NE=FW3, Layer=OCh, CTP=1\"}," + "{\"portId\":\"NE=FW3, Layer=OCh, CTP=2\"}" + "],"
            + "\"link\":" + "[" + "{\"linkId\":\"Layer=OCh, TL=1\",\"srcTTP\":\"NE=FW1, Layer=OCh,"
            + "TTP=1\",\"dstTTP\":\"NE=FW2, Layer=OCh, TTP=1\"},"
            + "{\"linkId\":\"Layer=OCh, TL=2\",\"srcTTP\":\"NE=FW2, Layer=OCh,"
            + "TTP=2\",\"dstTTP\":\"NE=FW3, Layer=OCh, TTP=1\"}" + "]" + "}}";

    Logger dummyLogger = mock(Logger.class);

    Field field = target.getClass().getSuperclass().getDeclaredField("logger");
    field.setAccessible(true);
    field.set(target, dummyLogger);

    Representation response = target.createNodeInfo(uppertestData);
    JSONObject result = new JSONObject(response.getText());

    verify(dummyLogger, times(1)).debug("make upper topology.");
    assertThat(result.getString("ResultLevel"), is("0"));
}