Java Code Examples for org.apache.commons.lang3.reflect.FieldUtils

The following examples show how to use org.apache.commons.lang3.reflect.FieldUtils. These examples are extracted from open source projects. 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 Project: webanno   Source File: AeroRemoteApiController.java    License: Apache License 2.0 6 votes vote down vote up
private static void forceOverwriteSofa(CAS aCas, String aValue)
{
    try {
        Sofa sofa = (Sofa) aCas.getSofa();
        MethodHandle _FH_sofaString = (MethodHandle) FieldUtils.readField(sofa,
                "_FH_sofaString", true);
        Method method = MethodUtils.getMatchingMethod(Sofa.class, "wrapGetIntCatchException",
                MethodHandle.class);
        int adjOffset;
        try {
            method.setAccessible(true);
            adjOffset = (int) method.invoke(null, _FH_sofaString);
        }
        finally {
            method.setAccessible(false);
        }
        sofa._setStringValueNcWj(adjOffset, aValue);
    }
    catch (Exception e) {
        throw new IllegalStateException("Cannot force-update SofA string", e);
    }
}
 
Example 2
Source Project: prebid-mobile-android   Source File: DemandFetcherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseConditions() throws Exception {
    PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
    PublisherAdRequest request = builder.build();
    DemandFetcher demandFetcher = new DemandFetcher(request);
    demandFetcher.setPeriodMillis(0);
    HashSet<AdSize> sizes = new HashSet<>();
    sizes.add(new AdSize(300, 250));
    RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
    demandFetcher.setRequestParams(requestParams);
    assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.start();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    demandFetcher.destroy();
    assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}
 
Example 3
Source Project: rqueue   Source File: RqueueMessageConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void rqueueMessageSenderWithMessageConverters() throws IllegalAccessException {
  SimpleRqueueListenerContainerFactory factory = new SimpleRqueueListenerContainerFactory();
  MessageConverter messageConverter = new GenericMessageConverter();
  RqueueListenerConfig messageConfig = new RqueueListenerConfig();
  factory.setMessageConverters(Collections.singletonList(messageConverter));
  FieldUtils.writeField(messageConfig, "simpleRqueueListenerContainerFactory", factory, true);
  factory.setRedisConnectionFactory(mock(RedisConnectionFactory.class));
  assertNotNull(messageConfig.rqueueMessageSender(rqueueMessageTemplate));
  RqueueMessageSender messageSender = messageConfig.rqueueMessageSender(rqueueMessageTemplate);
  boolean messageConverterIsConfigured = false;
  for (MessageConverter converter : messageSender.getMessageConverters()) {
    messageConverterIsConfigured =
        messageConverterIsConfigured || converter.hashCode() == messageConverter.hashCode();
  }
  assertTrue(messageConverterIsConfigured);
}
 
Example 4
Source Project: ogham   Source File: ResourceResolverAssertions.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> Set<T> findResolvers(RelativeResolver resolver, Class<T> resolverClass) {
	try {
		Set<T> found = new HashSet<>();
		if (resolverClass.isAssignableFrom(resolver.getClass())) {
			found.add((T) resolver);
		}
		ResourceResolver delegate = (ResourceResolver) FieldUtils.readField(resolver, "delegate", true);
		if (resolverClass.isAssignableFrom(resolver.getActualResourceResolver().getClass())) {
			found.add((T) delegate);
		}
		return found;
	} catch (IllegalAccessException e) {
		throw new IllegalStateException("Failed to get 'delegate' field of RelativeResolver", e);
	}
}
 
Example 5
/**
 *
 * This only overwrites favored nodes when there are none supplied.  I believe in later versions the favoredNodes are
 * populated for region groups.  When this happens, we will pass those favored nodes along.  Until then, we attempt to put the local
 * node in the favored nodes since sometimes Spark Tasks will run compactions remotely.
 *
 * @return
 * @throws IOException
 */
protected InetSocketAddress[] getFavoredNodes() throws IOException {
    try {
        RegionServerServices rsServices = (RegionServerServices) FieldUtils.readField(((HStore) store).getHRegion(), "rsServices", true);
        InetSocketAddress[] returnAddresses = (InetSocketAddress[]) MethodUtils.invokeMethod(rsServices,"getFavoredNodesForRegion",store.getRegionInfo().getEncodedName());
        if ( (returnAddresses == null || returnAddresses.length == 0)
                && store.getFileSystem() instanceof HFileSystem
                && ((HFileSystem)store.getFileSystem()).getBackingFs() instanceof DistributedFileSystem) {
            String[] txvr = conf.get("dfs.datanode.address").split(":"); // hack
            if (txvr.length == 2) {
                returnAddresses = new InetSocketAddress[1];
                returnAddresses[0] = new InetSocketAddress(hostName, Integer.parseInt(txvr[1]));
            }
            else {
                SpliceLogUtils.warn(LOG,"dfs.datanode.address is expected to have form hostname:port but is %s",txvr);
            }
        }
        return returnAddresses;
    } catch (Exception e) {
        SpliceLogUtils.error(LOG,e);
        throw new IOException(e);
    }

}
 
Example 6
Source Project: prebid-mobile-android   Source File: ResultCodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessForMoPub() throws Exception {

    HttpUrl httpUrl = server.url("/");
    Host.CUSTOM.setHostUrl(httpUrl.toString());
    PrebidMobile.setPrebidServerHost(Host.CUSTOM);
    PrebidMobile.setApplicationContext(activity.getApplicationContext());
    PrebidMobile.setPrebidServerAccountId("123456");
    server.enqueue(new MockResponse().setResponseCode(200).setBody(MockPrebidServerResponses.oneBidFromAppNexus()));
    BannerAdUnit adUnit = new BannerAdUnit("123456", 300, 250);
    MoPubView testView = new MoPubView(activity);
    OnCompleteListener mockListener = mock(OnCompleteListener.class);
    adUnit.fetchDemand(testView, mockListener);
    DemandFetcher fetcher = (DemandFetcher) FieldUtils.readField(adUnit, "fetcher", true);
    PrebidMobile.setTimeoutMillis(Integer.MAX_VALUE);
    ShadowLooper fetcherLooper = shadowOf(fetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    ShadowLooper demandLooper = shadowOf(fetcher.getDemandHandler().getLooper());
    demandLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    verify(mockListener).onComplete(ResultCode.SUCCESS);
    assertEquals("hb_pb:0.50,hb_env:mobile-app,hb_pb_appnexus:0.50,hb_size:300x250,hb_bidder_appnexus:appnexus,hb_bidder:appnexus,hb_cache_id:df4aba04-5e69-44b8-8608-058ab21600b8,hb_env_appnexus:mobile-app,hb_size_appnexus:300x250,hb_cache_id_appnexus:df4aba04-5e69-44b8-8608-058ab21600b8,", testView.getKeywords());

}
 
Example 7
Source Project: lucene-solr   Source File: HttpClientUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertSSLHostnameVerifier(Class<? extends HostnameVerifier> expected,
                                       SocketFactoryRegistryProvider provider) {
  ConnectionSocketFactory socketFactory = provider.getSocketFactoryRegistry().lookup("https");
  assertNotNull("unable to lookup https", socketFactory);
  assertTrue("socketFactory is not an SSLConnectionSocketFactory: " + socketFactory.getClass(),
             socketFactory instanceof SSLConnectionSocketFactory);
  SSLConnectionSocketFactory sslSocketFactory = (SSLConnectionSocketFactory) socketFactory;
  try {
    Object hostnameVerifier = FieldUtils.readField(sslSocketFactory, "hostnameVerifier", true);
    assertNotNull("sslSocketFactory has null hostnameVerifier", hostnameVerifier);
    assertEquals("sslSocketFactory does not have expected hostnameVerifier impl",
                 expected, hostnameVerifier.getClass());
  } catch (IllegalAccessException e) {
    throw new AssertionError("Unexpected access error reading hostnameVerifier field", e);
  }
}
 
Example 8
Source Project: arcusplatform   Source File: TestTwilioAckScriptHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
   super.setUp();
   builder = buildParameters(null);
   FieldUtils.writeField(handler, "twilioAccountAuth", "AUTHKEY", true);

   sig = Base64.encodeToString(HmacUtils.hmacSha1 ("AUTHKEY", TwilioHelper.PROTOCOL_HTTPS + "somehost" + builder.toString()));
   EasyMock.expect(request.getUri()).andReturn(builder.toString()).anyTimes();
   EasyMock.expect(request.getMethod()).andReturn(HttpMethod.GET);
   EasyMock.expect(request.headers()).andReturn(httpHeaders).anyTimes();
   
   EasyMock.expect(httpHeaders.contains(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(true).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(sig).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.HOST_HEADER_KEY)).andReturn("somehost").anyTimes();
   EasyMock.expect(personDAO.findById(personID)).andReturn(person);
   EasyMock.expect(placeDAO.findById(placeId)).andReturn(place);
   EasyMock.expect(populationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
}
 
Example 9
@SuppressWarnings("unchecked")
public void check(JpaObject jpa, CheckRemoveType checkRemoveType) throws Exception {
	for (Entry<Field, CheckRemove> entry : entityManagerContainerFactory.getCheckRemoveFields(jpa.getClass())
			.entrySet()) {
		Field field = entry.getKey();
		CheckRemove checkRemove = entry.getValue();
		FieldType fieldType = this.getFieldType(entry.getKey());
		// Object object = jpa.get(field.getName());
		Object object = FieldUtils.readField(field, jpa, true);
		switch (fieldType) {
			case stringValue:
				this.removeChecker.stringValue.check(field, null == object ? null : Objects.toString(object), jpa,
						checkRemove, checkRemoveType);
				break;
			case stringValueList:
				this.removeChecker.stringValueList.check(field, null == object ? null : (List<String>) object, jpa,
						checkRemove, checkRemoveType);
				break;
			default:
				break;
		}
	}
}
 
Example 10
Source Project: dremio-oss   Source File: ConnectionConf.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clears all fields that match a particular predicate. For all primitive types, the value is set
 * to zero. For object types, the value is set to null.
 *
 * @param predicate
 */
private void clear(Predicate<Field> predicate, boolean isSecret) {
  try {
    for(Field field : FieldUtils.getAllFields(getClass())) {
      if(predicate.apply(field)) {
        if (isSecret && field.getType().equals(String.class)) {
          final String value = (String) field.get(this);

          if (Strings.isNullOrEmpty(value)) {
            field.set(this, null);
          } else {
            field.set(this, USE_EXISTING_SECRET_VALUE);
          }
        } else {
          Object defaultValue = Defaults.defaultValue(field.getType());
          field.set(this, defaultValue);
        }
      }
    }
  } catch (IllegalAccessException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 11
Source Project: library   Source File: LdapObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method used to extract the values from a given attribute and put it into the domain model object
 *
 * @param clazz to instantiate the domain object
 * @param attributes to extract the values
 * @return an {@link Optional} of the domain object
 */
private Optional<T> extractValue(Class<T> clazz, Attributes attributes) {

    try {
        final T instance = clazz.getDeclaredConstructor().newInstance();

        final List<Field> fields = FieldUtils.getFieldsListWithAnnotation(instance.getClass(), LdapAttribute.class);

        for (Field field : fields) {
            final LdapAttribute annotation = field.getAnnotation(LdapAttribute.class);

            final Attribute attribute = attributes.get(annotation.value());

            if (attribute != null) {
                FieldUtils.writeField(field, instance, attribute.get(), true);
            }
        }
        return Optional.of(instance);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return Optional.empty();
}
 
Example 12
Source Project: cuba   Source File: EmbeddedAttributesMappingProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(MappingProcessorContext context) {
    DatabaseMapping mapping = context.getMapping();
    if (mapping instanceof AggregateObjectMapping) {
        ClassDescriptor descriptor = mapping.getDescriptor();
        Field referenceField =
                FieldUtils.getFieldsListWithAnnotation(descriptor.getJavaClass(), EmbeddedParameters.class)
                        .stream().filter(f -> f.getName().equals(mapping.getAttributeName())).findFirst().orElse(null);
        if (referenceField != null) {
            EmbeddedParameters embeddedParameters =
                    referenceField.getAnnotation(EmbeddedParameters.class);
            if (!embeddedParameters.nullAllowed())
                ((AggregateObjectMapping) mapping).setIsNullAllowed(false);
        }
    }
}
 
Example 13
Source Project: MicroCommunity   Source File: BeanConvertUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void objectFieldsPutMap(Object dstBean, BeanMap beanMap, Map orgMap) {
    //Field[] fields = dstBean.getClass().getDeclaredFields();
    Field[] fields = FieldUtils.getAllFields(dstBean.getClass());
    for (Field field : fields) {
        if (!orgMap.containsKey(field.getName())) {
            continue;
        }
        Class dstClass = field.getType();
        //System.out.println("字段类型" + dstClass);

        Object value = orgMap.get(field.getName());
        //String 转date
        Object tmpValue = Java110Converter.getValue(value, dstClass);
        beanMap.put(field.getName(), tmpValue);
    }
}
 
Example 14
Source Project: o2oa   Source File: ListTools.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T, W> List<T> extractField(List<W> list, String name, Class<T> clz, Boolean ignoreNull,
		Boolean unique) throws Exception {
	List<T> values = new ArrayList<>();
	if (isEmpty(list)) {
		return values;
	}
	for (W w : list) {
		Object o = FieldUtils.readField(w, name, true);
		if (null == o && ignoreNull) {
			continue;
		}
		if (unique && values.contains(o)) {
			continue;
		}
		if (null == o) {
			values.add(null);
		} else {
			values.add((T) o);
		}
	}
	return values;
}
 
Example 15
Source Project: dremio-oss   Source File: TestOptimisticByteOutput.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRopeByteStringWithZeroOnRight() throws Exception {
  ByteString literal = ByteString.copyFrom(smallData);

  ByteString data = (ByteString) NEW_ROPE_BYTE_STRING_INSTANCE.invoke(null, literal, ByteString.EMPTY);

  OptimisticByteOutput byteOutput = new OptimisticByteOutput(smallData.length);
  UnsafeByteOperations.unsafeWriteTo(data, byteOutput);

  byte[] array = (byte[]) FieldUtils.readField(literal, "bytes", true);
  assertArrayEquals(smallData, byteOutput.toByteArray());
  assertSame(array, byteOutput.toByteArray());
}
 
Example 16
Source Project: glitr   Source File: ReflectionUtil.java    License: MIT License 5 votes vote down vote up
public static String getDescriptionFromAnnotatedField(Class clazz, Method method) {
    try {
        Field field = FieldUtils.getField(clazz, ReflectionUtil.sanitizeMethodName(method.getName()), true);
        return ReflectionUtil.getDescriptionFromAnnotatedElement(field);
    } catch (Exception e) {
        logger.debug("Could not find a Field associated to the Method [{}]", method.getName());
    }
    return null;
}
 
Example 17
Source Project: cuba   Source File: BaseEntityInternalAccess.java    License: Apache License 2.0 5 votes vote down vote up
public static void setValueForHolder(Entity entity, String attribute, @Nullable Object value) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), String.format("_persistence_%s_vh",attribute), true);
    if (field == null)
        return;
    try {
        field.set(entity, value);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}
 
Example 18
Source Project: rqueue   Source File: RqueueListenerAutoConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void rqueueMessageSenderWithMessageTemplate() throws IllegalAccessException {
  SimpleRqueueListenerContainerFactory factory = new SimpleRqueueListenerContainerFactory();
  RqueueMessageTemplate messageTemplate = mock(RqueueMessageTemplate.class);
  factory.setRqueueMessageTemplate(messageTemplate);
  RqueueListenerAutoConfig messageAutoConfig = new RqueueListenerAutoConfig();
  FieldUtils.writeField(messageAutoConfig, "simpleRqueueListenerContainerFactory", factory, true);
  assertNotNull(messageAutoConfig.rqueueMessageSender(messageTemplate));
  assertEquals(factory.getRqueueMessageTemplate().hashCode(), messageTemplate.hashCode());
}
 
Example 19
Source Project: rqueue   Source File: RqueueMessageConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void rqueueMessageSenderWithMessageTemplate() throws IllegalAccessException {
  SimpleRqueueListenerContainerFactory factory = new SimpleRqueueListenerContainerFactory();
  RqueueMessageTemplate messageTemplate = mock(RqueueMessageTemplate.class);
  factory.setRqueueMessageTemplate(messageTemplate);
  RqueueListenerConfig messageConfig = new RqueueListenerConfig();
  FieldUtils.writeField(messageConfig, "simpleRqueueListenerContainerFactory", factory, true);
  assertNotNull(messageConfig.rqueueMessageSender(messageTemplate));
  assertEquals(factory.getRqueueMessageTemplate().hashCode(), messageTemplate.hashCode());
}
 
Example 20
Source Project: rqueue   Source File: RqueueTaskAggregatorServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void initService() throws IllegalAccessException {
  doReturn(true).when(rqueueWebConfig).isCollectListenerStats();
  doReturn(1).when(rqueueWebConfig).getStatsAggregatorThreadCount();
  doReturn(100).when(rqueueWebConfig).getAggregateEventWaitTime();
  doReturn(100).when(rqueueWebConfig).getAggregateShutdownWaitTime();
  doReturn(180).when(rqueueWebConfig).getHistoryDay();
  doReturn(500).when(rqueueWebConfig).getAggregateEventCount();
  this.rqueueTaskAggregatorService.start();
  assertNotNull(
      FieldUtils.readField(this.rqueueTaskAggregatorService, "queueNameToEvents", true));
  assertNotNull(FieldUtils.readField(this.rqueueTaskAggregatorService, "queue", true));
  assertNotNull(FieldUtils.readField(this.rqueueTaskAggregatorService, "taskExecutor", true));
}
 
Example 21
Source Project: rqueue   Source File: MetricsPropertiesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getMetricTags() throws IllegalAccessException {
  MetricProperties metricProperties = new MetricProperties();
  Map<String, String> tags = Collections.singletonMap("test", "test");
  FieldUtils.writeField(metricProperties, "tags", tags, true);
  assertEquals(Tags.of("test", "test"), metricProperties.getMetricTags());
}
 
Example 22
Source Project: o2oa   Source File: DescribeBuilder.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/** 判断字段是否在Wi中但是没有在Entity类中说明是Wi新增字段,需要进行描述 */
private Boolean inWiNotInEntity(String field, Class<?> clz) {
	try {
		Object o = FieldUtils.readStaticField(clz, "copier", true);
		WrapCopier copier = (WrapCopier) o;
		if ((null != FieldUtils.getField(copier.getOrigClass(), field, true))
				&& (null == FieldUtils.getField(copier.getDestClass(), field, true))) {
			return true;
		}
		return false;
	} catch (Exception e) {
		return null;
	}
}
 
Example 23
Source Project: cognition   Source File: ConfigurableIngestTopology.java    License: Apache License 2.0 5 votes vote down vote up
protected void configureStorm(Configuration conf, Config stormConf) throws IllegalAccessException {
  stormConf.registerSerialization(LogRecord.class);
  //stormConf.registerSerialization(Entity.class);
  stormConf.registerMetricsConsumer(LoggingMetricsConsumer.class);

  for (Iterator<String> iter = conf.getKeys(); iter.hasNext(); ) {
    String key = iter.next();

    String keyString = key.toString();
    String cleanedKey = keyString.replaceAll("\\.\\.", ".");

    String schemaFieldName = cleanedKey.replaceAll("\\.", "_").toUpperCase() + "_SCHEMA";
    Field field = FieldUtils.getField(Config.class, schemaFieldName);
    Object fieldObject = field.get(null);

    if (fieldObject == Boolean.class)
      stormConf.put(cleanedKey, conf.getBoolean(keyString));
    else if (fieldObject == String.class)
      stormConf.put(cleanedKey, conf.getString(keyString));
    else if (fieldObject == ConfigValidation.DoubleValidator)
      stormConf.put(cleanedKey, conf.getDouble(keyString));
    else if (fieldObject == ConfigValidation.IntegerValidator)
      stormConf.put(cleanedKey, conf.getInt(keyString));
    else if (fieldObject == ConfigValidation.PowerOf2Validator)
      stormConf.put(cleanedKey, conf.getLong(keyString));
    else if (fieldObject == ConfigValidation.StringOrStringListValidator)
      stormConf.put(cleanedKey, Arrays.asList(conf.getStringArray(keyString)));
    else if (fieldObject == ConfigValidation.StringsValidator)
      stormConf.put(cleanedKey, Arrays.asList(conf.getStringArray(keyString)));
    else {
      logger.error("{} cannot be configured from XML. Consider configuring in navie storm configuration.");
      throw new UnsupportedOperationException(cleanedKey + " cannot be configured from XML");
    }
  }
}
 
Example 24
private void checkPermissionOnResourceObjectFields(String userCrn, Object resourceObject) {
    Arrays.stream(FieldUtils.getFieldsWithAnnotation(resourceObject.getClass(), ResourceObjectField.class)).forEach(field -> {
        try {
            field.setAccessible(true);
            ResourceObjectField resourceObjectField = field.getAnnotation(ResourceObjectField.class);
            Object resultObject = field.get(resourceObject);
            AuthorizationResourceAction action = resourceObjectField.action();
            AuthorizationVariableType authorizationVariableType = resourceObjectField.variableType();
            switch (authorizationVariableType) {
                case NAME:
                    checkPermissionForResourceName(userCrn, resultObject, action);
                    break;
                case CRN:
                    checkPermissionForResourceCrn(userCrn, resultObject, action);
                    break;
                case NAME_LIST:
                    checkPermissionForResourceNameList(userCrn, resultObject, action);
                    break;
                case CRN_LIST:
                    checkPermissionForResourceCrnList(userCrn, resultObject, action);
                    break;
                default:
                    throw new AccessDeniedException("We cannot determine the type of field from authorization point of view, " +
                            "thus access is denied!");
            }
        } catch (NotFoundException nfe) {
            LOGGER.warn("Resource not found during permission check of resource object, this should be handled by microservice.");
        } catch (Error | RuntimeException unchecked) {
            LOGGER.error("Error happened while traversing the resource object: ", unchecked);
            throw unchecked;
        } catch (Throwable t) {
            LOGGER.error("Error happened while traversing the resource object: ", t);
            throw new AccessDeniedException("Error happened during permission check of resource object, thus access is denied!", t);
        }
    });
}
 
Example 25
Source Project: rqueue   Source File: RqueueMessageListenerContainerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checkDoStopMethodIsCalled() throws Exception {
  StubMessageSchedulerListenerContainer container = new StubMessageSchedulerListenerContainer();
  FieldUtils.writeField(
      container, "applicationEventPublisher", mock(ApplicationEventPublisher.class), true);
  container.afterPropertiesSet();
  container.start();
  container.stop();
  assertTrue(container.isDoStopMethodIsCalled());
}
 
Example 26
Source Project: rqueue   Source File: RqueueMessageListenerContainerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void checkDoStopMethodIsCalledWithRunnable() throws Exception {
  StubMessageSchedulerListenerContainer container = new StubMessageSchedulerListenerContainer();
  FieldUtils.writeField(
      container, "applicationEventPublisher", mock(ApplicationEventPublisher.class), true);
  CountDownLatch count = new CountDownLatch(1);
  container.afterPropertiesSet();
  container.start();
  container.stop(count::countDown);

  container.destroy();
  assertTrue(container.isDestroyMethodIsCalled());
  assertEquals(0, count.getCount());
}
 
Example 27
Source Project: rqueue   Source File: RqueueMessageListenerContainerTest.java    License: Apache License 2.0 5 votes vote down vote up
private RqueueMessageListenerContainer createContainer(
    RqueueMessageHandler messageHandler, RqueueMessageTemplate rqueueMessageTemplate)
    throws IllegalAccessException {
  RqueueMessageListenerContainer container =
      new RqueueMessageListenerContainer(messageHandler, rqueueMessageTemplate);
  FieldUtils.writeField(
      container, "applicationEventPublisher", mock(ApplicationEventPublisher.class), true);
  FieldUtils.writeField(
      container, "rqueueMessageMetadataService", mock(RqueueMessageMetadataService.class), true);
  RqueueConfig rqueueConfig = new RqueueConfig(null, true, 1);
  FieldUtils.writeField(container, "rqueueConfig", rqueueConfig, true);
  return container;
}
 
Example 28
@Test
public void collect() throws IllegalAccessException, IOException {
  new Expectations(RegistrationManager.INSTANCE) {
    {
      RegistrationManager.INSTANCE.getAppId();
      result = "testAppId";
    }
  };
  ArchaiusUtils.setProperty(PrometheusPublisher.METRICS_PROMETHEUS_ADDRESS, "localhost:0");
  publisher.init(globalRegistry, null, null);

  Registry registry = new DefaultRegistry(new ManualClock());
  globalRegistry.add(registry);

  Counter counter = registry.counter("count.name", "tag1", "tag1v", "tag2", "tag2v");
  counter.increment();

  HTTPServer httpServer = (HTTPServer) FieldUtils.readField(publisher, "httpServer", true);
  com.sun.net.httpserver.HttpServer server = (HttpServer) FieldUtils.readField(httpServer, "server", true);

  URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/metrics");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  try (InputStream is = conn.getInputStream()) {
    Assert.assertEquals("# HELP ServiceComb_Metrics ServiceComb Metrics\n" +
            "# TYPE ServiceComb_Metrics untyped\n" +
            "count_name{appId=\"testAppId\",tag1=\"tag1v\",tag2=\"tag2v\",} 1.0\n",
        IOUtils.toString(is, StandardCharsets.UTF_8));
  }

  publisher.destroy();
}
 
Example 29
private void injectResource(final Object provider) throws IllegalAccessException {
    final Field[] resourceFieldArray = FieldUtils.getFieldsWithAnnotation(provider.getClass(), Resource.class);
    if (ArrayUtils.isEmpty(resourceFieldArray)) {
        return;
    }
    for (final Field resourceField : resourceFieldArray) {
        final Class<?> fieldType = resourceField.getType();
        // ConfigInfo注入
        if (ConfigInfo.class.isAssignableFrom(fieldType)) {
            final ConfigInfo configInfo = new DefaultConfigInfo(cfg);
            FieldUtils.writeField(resourceField, provider, configInfo, true);
        }
    }
}
 
Example 30
Source Project: cloudbreak   Source File: EntityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIfClassesWithSecretFieldsAreInheritedFromTenantOrWorkspaceAwareResources() {
    Reflections reflections = new Reflections("com.sequenceiq");
    Set<Class<?>> entityClasses = reflections.getTypesAnnotatedWith(Entity.class);
    Set<Class<?>> wrongClasses = entityClasses.stream()
            .filter(cls -> FieldUtils.getFieldsWithAnnotation(cls, SecretValue.class).length > 0)
            .filter(cls -> !TenantAwareResource.class.isAssignableFrom(cls))
            .collect(Collectors.toSet());
    Assert.assertTrue(
            String.format("Classes with Secret fields should be inherited from TenantAwareResource or WorkspaceAwareResoruce. Wrong classes: %s",
                    wrongClasses.stream().map(Class::getName).collect(Collectors.joining(", "))), wrongClasses.isEmpty());
}