Java Code Examples for java.lang.reflect.Field#set()

The following examples show how to use java.lang.reflect.Field#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeycloakRefreshTokenTest.java    From camunda-bpm-identity-keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Tests refreshing access token.
 * @throws Exception in case of errors
 */
public void testRefreshToken() throws Exception {
	// access Keycloak
    assertEquals(5, identityService.createUserQuery().count());

    // expire current token (the dirty way)
    KeycloakIdentityProviderFactory sessionFacory = (KeycloakIdentityProviderFactory) 
    		((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).getIdentityProviderSessionFactory();
    KeycloakContextProvider keycloakContextProvider = getProtectedField(sessionFacory, "keycloakContextProvider");
    KeycloakContext ctx = getProtectedField(keycloakContextProvider, "context");
    Field expiresField = KeycloakContext.class.getDeclaredField("expiresAt");
    expiresField.setAccessible(true);
    expiresField.set(ctx, 0);
    assertTrue(ctx.needsRefresh());
    
	// access Keycloak again
    assertEquals(5, identityService.createUserQuery().count());
    
}
 
Example 2
Source File: WithPod.java    From dekorate with Apache License 2.0 6 votes vote down vote up
/**
 * Inject a {@link Pod} to the specified {@link Field}.
 * The pod is matched using its corresponding endpoints.
 * In other words this acts like `inject pod of service`
 * @param context      The execution context.
 * @param testInstance The target test instance.
 * @param field        The field to inject.
 */
default void injectPod(ExtensionContext context, Object testInstance, Field field) {
  if (!field.getType().isAssignableFrom(Pod.class)) {
    return;
  }

  //This is to make sure we don't write on fields by accident.
  //Note: we don't require the exact annotation. Any annotation named Inject will do (be it javax, guice etc)
  if (!stream(field.getDeclaredAnnotations()).filter(a -> a.annotationType().getSimpleName().equalsIgnoreCase("Inject")).findAny().isPresent()) {
    return;
  }

  String name = namedAnnotation(field).orElseGet(() -> getName());
  field.setAccessible(true);
  try {
    field.set(testInstance, podForName(context, name));
  } catch (IllegalAccessException e) {
    throw DekorateException.launderThrowable(e);
  }
}
 
Example 3
Source File: JsonDataModelInjector.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Injects text data model on the filed of work-let.
 *
 * @param worklet work-let
 * @param context workflow context
 * @param field   the field of work-let
 * @param model   text data model for the field
 * @throws WorkflowException workflow exception
 */
private static void injectText(Worklet worklet, WorkflowContext context, Field field, JsonDataModel model)
        throws WorkflowException {

    String text = ((JsonDataModelTree) context.data()).textAt(model.path());
    if (Objects.isNull(text)) {
        if (model.optional()) {
            return;
        }
        throw new WorkflowException("Invalid text data model on (" + model.path() + ")");
    }

    if (!(Objects.equals(field.getType(), String.class))) {
        throw new WorkflowException("Target field (" + field + ") is not String");
    }

    try {
        field.setAccessible(true);
        field.set(worklet, text);
    } catch (IllegalAccessException e) {
        throw new WorkflowException(e);
    }
}
 
Example 4
Source File: MqQueueExcutorServiceTest.java    From pmq with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendFailMailfailBeginTime50()
		throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
	MockMqClientBase mockMqClientBase = new MockMqClientBase();
	ConsumerQueueDto consumerQueueDto = buildDefaultConsumerQueueDto();
	consumerQueueDto.setPullBatchSize(20);
	MqQueueExcutorService mqQueueExcutorService = new MqQueueExcutorService(mockMqClientBase, consumerGroupName,
			consumerQueueDto);
	Field field = mqQueueExcutorService.getClass().getDeclaredField("failBeginTime");
	field.setAccessible(true);
	field.set(mqQueueExcutorService, System.currentTimeMillis() - 1);
	mqQueueExcutorService.sendFailMail();

	assertEquals("testSendFailMailfailBeginTime50 error", 0,
			((MqQueueResource) mockMqClientBase.getContext().getMqResource()).getSendMailFlag());
}
 
Example 5
Source File: ImageIcon.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public Component run() {
    try {
        final Component component = createNoPermsComponent();

        // 6482575 - clear the appContext field so as not to leak it
        Field appContextField =

                Component.class.getDeclaredField("appContext");
        appContextField.setAccessible(true);
        appContextField.set(component, null);

        return component;
    } catch (Throwable e) {
        // We don't care about component.
        // So don't prevent class initialisation.
        e.printStackTrace();
        return null;
    }
}
 
Example 6
Source File: QuotaTariffListCmdTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuotaTariffListCmd() throws NoSuchFieldException, IllegalAccessException {
    QuotaTariffListCmd cmd = new QuotaTariffListCmd();

    Field rbField = QuotaTariffListCmd.class.getDeclaredField("_responseBuilder");
    rbField.setAccessible(true);
    rbField.set(cmd, responseBuilder);

    List<QuotaTariffVO> quotaTariffVOList = new ArrayList<QuotaTariffVO>();
    QuotaTariffVO tariff = new QuotaTariffVO();
    tariff.setEffectiveOn(new Date());
    tariff.setCurrencyValue(new BigDecimal(100));
    tariff.setUsageType(QuotaTypes.MEMORY);

    quotaTariffVOList.add(new QuotaTariffVO());
    Mockito.when(responseBuilder.listQuotaTariffPlans(Mockito.eq(cmd))).thenReturn(quotaTariffVOList);
    Mockito.when(responseBuilder.createQuotaTariffResponse(Mockito.any(QuotaTariffVO.class))).thenReturn(new QuotaTariffResponse());

    cmd.execute();
    Mockito.verify(responseBuilder, Mockito.times(1)).createQuotaTariffResponse(Mockito.any(QuotaTariffVO.class));
}
 
Example 7
Source File: RpcActionNode.java    From sumk with Apache License 2.0 6 votes vote down vote up
public Object invokeByOrder(String... args) throws Throwable {
	if (this.isEmptyArgument()) {
		return this.execute(this.getEmptyArgObj());
	}
	if (args == null) {
		SumkException.throwException(12012, method.getName() + "的参数不能为空");
	}
	if (args.length != argNames.length) {
		Logs.rpc().debug(method.getName() + "需要传递" + argNames.length + "个参数,实际传递" + args.length + "个");
	}

	ArgPojo pojo = Loader.newInstance(this.argClz);
	for (int i = 0; i < fields.length; i++) {
		if (i >= args.length || args[i] == null) {
			continue;
		}
		Field f = fields[i];
		f.set(pojo, RpcGson.fromJson(args[i], f.getGenericType()));
	}
	return this.execute(pojo);
}
 
Example 8
Source File: SendMsgStatusCommandTest.java    From rocketmq-4.3.0 with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException, RemotingTimeoutException, MQClientException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
    mQClientAPIImpl = mock(MQClientAPIImpl.class);
    defaultMQAdminExt = new DefaultMQAdminExt();
    defaultMQAdminExtImpl = new DefaultMQAdminExtImpl(defaultMQAdminExt, 1000);

    Field field = DefaultMQAdminExtImpl.class.getDeclaredField("mqClientInstance");
    field.setAccessible(true);
    field.set(defaultMQAdminExtImpl, mqClientInstance);
    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mqClientInstance, mQClientAPIImpl);
    field = DefaultMQAdminExt.class.getDeclaredField("defaultMQAdminExtImpl");
    field.setAccessible(true);
    field.set(defaultMQAdminExt, defaultMQAdminExtImpl);
}
 
Example 9
Source File: KafkaSinkTest.java    From flume-ng-kafka-sink with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
	mockProducer = mock(Producer.class);
	mockChannel = mock(Channel.class);
	mockEvent = mock(Event.class);
	mockTx = mock(Transaction.class);
	mockKafkaSink = new KafkaSink();
	
	Field field = AbstractSink.class.getDeclaredField("channel");
	field.setAccessible(true);
	field.set(mockKafkaSink, mockChannel);

	field = KafkaSink.class.getDeclaredField("topic");
	field.setAccessible(true);
	field.set(mockKafkaSink, "test");

	field = KafkaSink.class.getDeclaredField("producer");
	field.setAccessible(true);
	field.set(mockKafkaSink, mockProducer);
	
	when(mockChannel.take()).thenReturn(mockEvent);
	when(mockChannel.getTransaction()).thenReturn(mockTx);
}
 
Example 10
Source File: TrustAllSSLSocketFactory.java    From GOpenSource_AppKit_Android_AS with MIT License 5 votes vote down vote up
private void injectHostname(Socket socket, String host) {
  try {
    Field field = InetAddress.class.getDeclaredField("hostName");
    field.setAccessible(true);
    field.set(socket.getInetAddress(), host);
  } catch (Exception ignored) {
  }
}
 
Example 11
Source File: JavaActionProviderTestSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean setUserPropertiesPolicy(
        @NonNull JavaActionProvider jap,
        @NullAllowed ActionProviderSupport.UserPropertiesPolicy policy) {
    try {
        final Field f = JavaActionProvider.class.getDeclaredField("userPropertiesPolicy");
        f.setAccessible(true);
        f.set(jap, policy);
        return true;
    } catch (ReflectiveOperationException e) {
        return false;
    }
}
 
Example 12
Source File: CrudService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
public int save(T t) {
	t.setCreateDate(new Date());
	t.setUpdateDate(t.getCreateDate());
	if (StringUtils.isEmpty(t.getCreateBy())) {
		t.setCreateBy(this.getOperatorUserId());
	}
	t.setUpdateBy(t.getCreateBy());
	//自增主键的insert sql 不能出现插入id 
	if (null == t.getId() || StringUtils.isEmpty(t.getId().toString())) {
		Class<?> clazz = t.getClass();  
	    Type type = clazz.getGenericSuperclass();  
	    ParameterizedType parameterizedType = (ParameterizedType) type;  
	    if (parameterizedType.getActualTypeArguments()[0].equals(String.class)) {
	    		//t.setId(IdGen.uuid()); 这个要是编译可以过去就不用这么麻烦去获取主键类型
	    		Field findField = ReflectionUtils.findField(clazz, "id");
	    		try {
	    			    findField.setAccessible(true);
					findField.set(t, IdGen.uuid());
			} catch (Exception e) {
				logger.error("set id error:",e);
			} 
	    }
	}
	
	int cnt = d.insert(t);
	if (t.isNeedBak()) {
		this.saveBak(t.getId());
	}
	return cnt;
}
 
Example 13
Source File: VirtSet.java    From radon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(VM vm, Object[] operands) throws Exception {
    String ownerName = (String) operands[0];
    String name = (String) operands[1];
    String typeName = (String) operands[2];

    Class clazz = VM.getClazz(ownerName);
    Class type = VM.getClazz(typeName);
    Field field = VM.getField(clazz, name, type);

    if (field == null)
        throw new VMException();

    JWrapper value = vm.pop();

    if (value instanceof JTop)
        value = vm.pop();

    Object ref = vm.pop().asObj();

    if ("int".equals(ownerName))
        field.setInt(ref, value.asInt());
    else if ("long".equals(ownerName))
        field.setLong(ref, value.asLong());
    else if ("float".equals(ownerName))
        field.setFloat(ref, value.asFloat());
    else if ("double".equals(ownerName))
        field.setDouble(ref, value.asDouble());
    else if ("byte".equals(ownerName))
        field.setByte(ref, value.asByte());
    else if ("short".equals(ownerName))
        field.setShort(ref, value.asShort());
    else if ("char".equals(ownerName))
        field.setChar(ref, value.asChar());
    else if ("boolean".equals(ownerName))
        field.setBoolean(ref, value.asBool());
    else
        field.set(ref, value.asObj());
}
 
Example 14
Source File: ReflectionUtil.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public static void setSuperValue(Object instance, String fieldName,
		Object value) throws Exception
{
	Field field = instance.getClass().getSuperclass()
			.getDeclaredField(fieldName);
	field.setAccessible(true);
	field.set(instance, value);
}
 
Example 15
Source File: VolumeApiServiceImplTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetachVolumeFromStoppedXenVm() throws NoSuchFieldException, IllegalAccessException {
    thrown.expect(NullPointerException.class);
    Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
    dedicateIdField.setAccessible(true);
    dedicateIdField.set(detachCmd, 2L);
    volumeApiServiceImpl.detachVolumeFromVM(detachCmd);
}
 
Example 16
Source File: QuotaResponseBuilderImplTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IllegalAccessException, NoSuchFieldException {
    // Dummy transaction stack setup
    TransactionLegacy.open("QuotaResponseBuilderImplTest");

    Field tariffDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaTariffDao");
    tariffDaoField.setAccessible(true);
    tariffDaoField.set(quotaResponseBuilder, quotaTariffDao);

    Field balanceDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaBalanceDao");
    balanceDaoField.setAccessible(true);
    balanceDaoField.set(quotaResponseBuilder, quotaBalanceDao);

    Field quotaCreditsDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaCreditsDao");
    quotaCreditsDaoField.setAccessible(true);
    quotaCreditsDaoField.set(quotaResponseBuilder, quotaCreditsDao);

    Field quotaEmailTemplateDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaEmailTemplateDao");
    quotaEmailTemplateDaoField.setAccessible(true);
    quotaEmailTemplateDaoField.set(quotaResponseBuilder, quotaEmailTemplateDao);

    Field userDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_userDao");
    userDaoField.setAccessible(true);
    userDaoField.set(quotaResponseBuilder, userDao);

    Field quotaServiceField = QuotaResponseBuilderImpl.class.getDeclaredField("_quotaService");
    quotaServiceField.setAccessible(true);
    quotaServiceField.set(quotaResponseBuilder, quotaService);

    Field accountDaoField = QuotaResponseBuilderImpl.class.getDeclaredField("_accountDao");
    accountDaoField.setAccessible(true);
    accountDaoField.set(quotaResponseBuilder, accountDao);

    Field regionMgrField = QuotaResponseBuilderImpl.class.getDeclaredField("_accountMgr");
    regionMgrField.setAccessible(true);
    regionMgrField.set(quotaResponseBuilder, accountMgr);
}
 
Example 17
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void readObject (final ObjectInputStream s) throws ClassNotFoundException, IOException {
    s.defaultReadObject( );
    try {
        Field f = this.getClass().getDeclaredField("logBuilder");
        f.setAccessible(true);
        f.set(this, new LocalLogBuilder(this));
    } catch (NoSuchFieldException | IllegalAccessException ex) {
        StatusLogger.getLogger().warn("Unable to initialize LogBuilder");
    }
}
 
Example 18
Source File: FieldSetter.java    From skywalking with Apache License 2.0 4 votes vote down vote up
public static <T> void setValue(Object instance, String fieldName,
    T value) throws IllegalAccessException, NoSuchFieldException {
    Field field = instance.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(instance, value);
}
 
Example 19
Source File: CountingSecurityManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean acceptFileWrite(String file) {
    String ud = System.getProperty("netbeans.user");
    if (ud == null) {
        // still initializing
        return false;
    }
    if (!startsWith(file, ud)) {
        return false;
    }

    String f = file.substring(ud.length()).replace(File.separatorChar, '/');
    if (f.startsWith("/.metadata")) {
        // equinox runtime
        return false;
    }
    if (f.contains("config/Modules")) {
        return false;
    }
    if (f.contains("config/Windows2Local")) {
        return false;
    }
    if (f.contains("var/cache/netigso")) {
        return false;
    }
    if (f.endsWith(".hg")) {
        try {
            Class<?> ref = Class.forName("org.netbeans.modules.versioning.util.Utils", true, Thread.currentThread().getContextClassLoader());
            Field unver = ref.getDeclaredField("unversionedFolders");
            unver.setAccessible(true);
            unver.set(null, new File[]{new File(ud).getParentFile()});
            return false;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    
    if (startsWith(file, ud)) {
        if (startsWith(f, "/")) {
            f = f.substring(1);
        }
        if (allowed.contains(f)) {
            return false;
        }
    }
    for (StackTraceElement e : Thread.currentThread().getStackTrace()) {
        if (e.getClassName().contains("junit.JUnitTestRunner")) {
            return false;
        }
        // this happens from time to time (according to GC being scheduled or not)
        // and shall not influence the results of this test
        if (e.getClassName().equals("org.openide.util.WeakListenerImpl$ListenerReference") && e.getMethodName().equals("getRemoveMethod")) {
            return false;
        }
    }

    return prefix == null || startsWith(file, prefix);
}
 
Example 20
Source File: CertServiceTest.java    From cosmic with Apache License 2.0 4 votes vote down vote up
@Test
public void runUploadSslCertExpiredCert() throws IOException, IllegalAccessException, NoSuchFieldException {

    // Reading appropritate files
    final String certFile = URLDecoder.decode(getClass().getResource("/certs/expired_cert.crt").getFile(), Charset.defaultCharset().name());
    final String keyFile = URLDecoder.decode(getClass().getResource("/certs/rsa_self_signed.key").getFile(), Charset.defaultCharset().name());

    final String cert = readFileToString(new File(certFile));
    final String key = readFileToString(new File(keyFile));

    final CertServiceImpl certService = new CertServiceImpl();

    //setting mock objects
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);

    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);

    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.persist(any(SslCertVO.class))).thenReturn(new SslCertVO());

    //creating the command
    final UploadSslCertCmd uploadCmd = new UploadSslCertCmdExtn();
    final Class<?> _class = uploadCmd.getClass().getSuperclass();

    final Field certField = _class.getDeclaredField("cert");
    certField.setAccessible(true);
    certField.set(uploadCmd, cert);

    final Field keyField = _class.getDeclaredField("key");
    keyField.setAccessible(true);
    keyField.set(uploadCmd, key);

    try {
        certService.uploadSslCert(uploadCmd);
        fail("Given an expired certificate, upload should fail");
    } catch (final Exception e) {
        assertTrue(e.getMessage().contains("Certificate expired"));
    }
}