@Override public Object run() { try { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletResponse response = ctx.getResponse(); if (!rateLimiter.tryAcquire()) { HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS; response.setContentType(MediaType.TEXT_PLAIN_VALUE); response.setStatus(httpStatus.value()); ctx.setResponseStatusCode(httpStatus.value()); ctx.setSendZuulResponse(false); } } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } return null; }
@Override public Object run() { try { RequestContext currentContext = RequestContext.getCurrentContext(); HttpServletResponse response = currentContext.getResponse(); if (!rateLimiter.tryAcquire()) { response.setContentType(MediaType.TEXT_PLAIN_VALUE); response.setStatus(this.tooManyRequests.value()); response.getWriter().append(this.tooManyRequests.getReasonPhrase()); currentContext.setSendZuulResponse(false); throw new ZuulException(this.tooManyRequests.getReasonPhrase(), this.tooManyRequests.value(), this.tooManyRequests.getReasonPhrase()); } } catch (Exception e) { ReflectionUtils.rethrowRuntimeException(e); } return null; }
@Override public void afterPropertiesSet() throws Exception { String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, Object.class); for(String beanName : beanNames){ Class<?> beanType = this.applicationContext.getType(beanName); if(beanType != null){ final Class<?> userType = ClassUtils.getUserClass(beanType); ReflectionUtils.doWithMethods(userType, method -> { if(AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class) != null) { ServiceMethodInfo info = new ServiceMethodInfo(method); logger.info("Registering remote endpoint at path {}, exchange {} for method {}", info.getMappingInfo().getPath(), info.getMappingInfo().getExchangeMode(), method); MethodHandler methodHandler = new MethodHandler(applicationContext.getBean(beanName), info); mappingHandlers.add(methodHandler); } }); } } initDefaultConverters(); }
private Object getAuthor(Event event) { if (event == null) { return null; } Class<? extends Event> clazz = event.getClass(); Method method; if (!userAccessors.containsKey(clazz)) { method = ReflectionUtils.findMethod(clazz, "getUser"); if (method == null) { method = ReflectionUtils.findMethod(clazz, "getAuthor"); } userAccessors.put(clazz, method); } else { method = userAccessors.get(clazz); } if (method != null) { Object result = ReflectionUtils.invokeMethod(method, event); if (result instanceof User) { return result; } } return null; }
public JBossModulesAdapter(ClassLoader loader) { this.classLoader = loader; try { Field transformer = ReflectionUtils.findField(loader.getClass(), "transformer"); transformer.setAccessible(true); this.delegatingTransformer = transformer.get(loader); if (!this.delegatingTransformer.getClass().getName().equals(DELEGATING_TRANSFORMER_CLASS_NAME)) { throw new IllegalStateException("Transformer not of the expected type DelegatingClassFileTransformer: " + this.delegatingTransformer.getClass().getName()); } this.addTransformer = ReflectionUtils.findMethod(this.delegatingTransformer.getClass(), "addTransformer", ClassFileTransformer.class); this.addTransformer.setAccessible(true); } catch (Exception ex) { throw new IllegalStateException("Could not initialize JBoss 7 LoadTimeWeaver", ex); } }
/** * Copy the properties of the supplied {@link Annotation} to the supplied target bean. * Any properties defined in {@code excludedProperties} will not be copied. * <p>A specified value resolver may resolve placeholders in property values, for example. * @param ann the annotation to copy from * @param bean the bean instance to copy to * @param valueResolver a resolve to post-process String property values (may be {@code null}) * @param excludedProperties the names of excluded properties, if any * @see org.springframework.beans.BeanWrapper */ public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) { Set<String> excluded = new HashSet<String>(Arrays.asList(excludedProperties)); Method[] annotationProperties = ann.annotationType().getDeclaredMethods(); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean); for (Method annotationProperty : annotationProperties) { String propertyName = annotationProperty.getName(); if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) { Object value = ReflectionUtils.invokeMethod(annotationProperty, ann); if (valueResolver != null && value instanceof String) { value = valueResolver.resolveStringValue((String) value); } bw.setPropertyValue(propertyName, value); } } }
public static <T> List<T> getSortedService(Class<T> serviceType) { List<Entry<Integer, T>> serviceEntries = new ArrayList<>(); ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceType); serviceLoader.forEach(service -> { int serviceOrder = 0; Method getOrder = ReflectionUtils.findMethod(service.getClass(), "getOrder"); if (getOrder != null) { serviceOrder = (int) ReflectionUtils.invokeMethod(getOrder, service); } Entry<Integer, T> entry = new SimpleEntry<>(serviceOrder, service); serviceEntries.add(entry); }); return serviceEntries.stream() .sorted(Comparator.comparingInt(Entry::getKey)) .map(Entry::getValue) .collect(Collectors.toList()); }
@Override public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException { try { if (arguments != null) { ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition); } if (this.method.isVarArgs()) { arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.method.getParameterTypes(), arguments); } ReflectionUtils.makeAccessible(this.method); Object value = this.method.invoke(target, arguments); return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.method, -1)).narrow(value)); } catch (Exception ex) { throw new AccessException("Problem invoking method: " + this.method, ex); } }
@Override public Object toCommand(LockedExternalTaskDto task) { ExternalTask<?> externalTask = getExternalTask(task.getTopicName()); Object command = JavaUtils.callWithoutCheckedException(() -> externalTask.getClazz().newInstance()); externalTask.getFields().forEach((varName, field) -> { if (task.getVariables() != null) { task.getVariables().computeIfPresent(varName, (name, value) -> { JavaUtils.setFieldWithoutCheckedException(field, command, value.getValue()); return value; }); } Field taskField = ReflectionUtils.findField(task.getClass(), varName); if (taskField != null) { ReflectionUtils.makeAccessible(taskField); JavaUtils.setFieldWithoutCheckedException(field, command, () -> taskField.get(task)); } }); return command; }
@Test public void overridingIntervalAndCollectionNameThroughAnnotationShouldWork() throws IllegalAccessException { this.context = new AnnotationConfigApplicationContext(); this.context.register(OverrideMongoParametersConfig.class); this.context.refresh(); ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class); Field inactiveField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "maxInactiveIntervalInSeconds"); ReflectionUtils.makeAccessible(inactiveField); Integer inactiveSeconds = (Integer) inactiveField.get(repository); Field collectionNameField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "collectionName"); ReflectionUtils.makeAccessible(collectionNameField); String collectionName = (String) collectionNameField.get(repository); assertThat(inactiveSeconds).isEqualTo(123); assertThat(collectionName).isEqualTo("test-case"); }
private Object getMainCommand(Collection<Object> candidates) { Object mainCommand = null; for (Object candidate : candidates) { Class<?> clazz = AopUtils.getTargetClass(candidate); Method method = ReflectionUtils.findMethod(Command.class, "name"); if (clazz.isAnnotationPresent(Command.class) && method != null && clazz.getAnnotation(Command.class).name().equals(method.getDefaultValue())) { mainCommand = candidate; break; } } if (mainCommand == null) { mainCommand = new PicocliCommand() {}; } return mainCommand; }
@Before public void init() { listener = new JmsExternalCommandListener(); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(JmsExternalCommandListener.class, "taskService") , listener , taskService ); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(JmsExternalCommandListener.class, "taskManager") , listener , taskManager ); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(JmsExternalCommandListener.class, "taskMapper") , listener , taskMapper ); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(JmsExternalCommandListener.class, "jmsTemplate") , listener , jmsTemplate ); }
/** * Convert the given RemoteException that happened during remote access * to Spring's RemoteAccessException if the method signature does not * support RemoteException. Else, return the original RemoteException. * @param method the invoked method * @param ex the RemoteException that happened * @param isConnectFailure whether the given exception should be considered * a connect failure * @param serviceName the name of the service (for debugging purposes) * @return the exception to be thrown to the caller */ public static Exception convertRmiAccessException( Method method, RemoteException ex, boolean isConnectFailure, String serviceName) { if (logger.isDebugEnabled()) { logger.debug("Remote service [" + serviceName + "] threw exception", ex); } if (ReflectionUtils.declaresException(method, ex.getClass())) { return ex; } else { if (isConnectFailure) { return new RemoteConnectFailureException("Could not connect to remote service [" + serviceName + "]", ex); } else { return new RemoteAccessException("Could not access remote service [" + serviceName + "]", ex); } } }
/** * Adds the cookie, taking into account {@link RememberMeCredential#REQUEST_PARAMETER_REMEMBER_ME} * in the request. * * @param request the request * @param response the response * @param cookieValue the cookie value */ public void addCookie(final HttpServletRequest request, final HttpServletResponse response, final String cookieValue) { final String theCookieValue = this.casCookieValueManager.buildCookieValue(cookieValue, request); if (!StringUtils.hasText(request.getParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME))) { super.addCookie(response, theCookieValue); } else { final Cookie cookie = createCookie(theCookieValue); cookie.setMaxAge(this.rememberMeMaxAge); if (isCookieSecure()) { cookie.setSecure(true); } if (isCookieHttpOnly()) { final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); if(setHttpOnlyMethod != null) { cookie.setHttpOnly(true); } else { logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0."); } } response.addCookie(cookie); } }
/** * 调用方法,可以是一些私有方法 * * @param target * @param methodName * @param args * @return * @throws Exception */ public static Object invokeMethod(Object target, String methodName, Object... args) throws Exception { Method method = null; // 查找对应的方法 if (args == null || args.length == 0) { method = ReflectionUtils.findMethod(target.getClass(), methodName); } else { Class[] argsClass = new Class[args.length]; for (int i = 0; i < args.length; i++) { argsClass[i] = args[i].getClass(); } method = ReflectionUtils.findMethod(target.getClass(), methodName, argsClass); } ReflectionUtils.makeAccessible(method); if (args == null || args.length == 0) { return ReflectionUtils.invokeMethod(method, target); } else { return ReflectionUtils.invokeMethod(method, target, args); } }
@Override public Guild getGuild(Event event) { if (event == null) { return null; } Class<? extends Event> clazz = event.getClass(); Method method; if (!guildAccessors.containsKey(clazz)) { method = ReflectionUtils.findMethod(clazz, "getGuild"); guildAccessors.put(clazz, method); } else { method = guildAccessors.get(clazz); } if (method != null) { Object result = ReflectionUtils.invokeMethod(method, event); if (result instanceof Guild) { return (Guild) result; } } return null; }
@PostLoad public void checking(Object target) { AnnotationCheckingMetadata metadata = AnnotationCheckingMetadata.getMetadata(target.getClass()); if (metadata.isCheckable()) { StringBuilder sb = new StringBuilder(); for (Field field : metadata.getCheckedFields()) { ReflectionUtils.makeAccessible(field); Object value = ReflectionUtils.getField(field, target); if (value instanceof Date) { throw new RuntimeException("不支持时间类型字段解密!"); } sb.append(value).append(" - "); } sb.append(MD5_KEY); LOGGER.debug("验证数据:" + sb); String hex = MD5Utils.encode(sb.toString()); Field checksumField = metadata.getCheckableField(); ReflectionUtils.makeAccessible(checksumField); String checksum = (String) ReflectionUtils.getField(checksumField, target); if (!checksum.equals(hex)) { //throw new RuntimeException("数据验证失败!"); } } }
/** * Retrieve all candidate methods for the given class, considering * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag. * Called as the starting point for factory method determination. */ private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedAction<Method[]>() { @Override public Method[] run() { return (mbd.isNonPublicAccessAllowed() ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } }); } else { return (mbd.isNonPublicAccessAllowed() ? ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()); } }
public DocumentDbEntityInformation(Class<T> domainClass) { super(domainClass); this.id = getIdField(domainClass); if (this.id != null) { ReflectionUtils.makeAccessible(this.id); } this.collectionName = getCollectionName(domainClass); this.partitionKeyField = getPartitionKeyField(domainClass); if (this.partitionKeyField != null) { ReflectionUtils.makeAccessible(this.partitionKeyField); } this.requestUnit = getRequestUnit(domainClass); }
/** * Return JPA managed properties. * * @param <T> * Bean type. * @param beanType * the bean type. * @return the headers built from given type. */ public <T> String[] getJpaHeaders(final Class<T> beanType) { // Build descriptor list respecting the declaration order final OrderedFieldCallback fieldCallBack = new OrderedFieldCallback(); ReflectionUtils.doWithFields(beanType, fieldCallBack); final List<String> orderedDescriptors = fieldCallBack.descriptorsOrdered; // Now filter the properties final List<String> descriptorsFiltered = new ArrayList<>(); final ManagedType<T> managedType = transactionManager.getEntityManagerFactory().getMetamodel().managedType(beanType); for (final String propertyDescriptor : orderedDescriptors) { for (final Attribute<?, ?> attribute : managedType.getAttributes()) { // Match only basic attributes if (attribute instanceof SingularAttribute<?, ?> && propertyDescriptor.equals(attribute.getName())) { descriptorsFiltered.add(attribute.getName()); break; } } } // Initialize the CSV reader return descriptorsFiltered.toArray(new String[descriptorsFiltered.size()]); }
/** * 设置枚举类型的字段值 * * @param target the target object from which to get the field * @param field the field to set * @param ordinal enum.ordinal * @throws Exception IllegalArgumentException, IllegalAccess */ @SuppressWarnings("rawtypes") public static void setFieldEnumValueByOrdinal(Object target, Field field, int ordinal) throws Exception { if (field.getType().isEnum()) { if (!field.isAccessible()) { ReflectionUtils.makeAccessible(field); } Enum[] enumObjs = (Enum[]) (field.getType()).getEnumConstants(); for (Enum enumObj : enumObjs) { if (enumObj.ordinal() == ordinal) { field.set(target, enumObj); } } } else { throw new ReflectionException(target.getClass().getName() + "." + field.getName() + ":field type is not Enum, can not convertToEnum"); } }
private String toString(DataSource dataSource) { if (dataSource == null) { return "<none>"; } else { try { Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url"); ReflectionUtils.makeAccessible(urlField); return stripCredentials((String) urlField.get(dataSource)); } catch (Exception fe) { try { Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl"); ReflectionUtils.makeAccessible(urlMethod); return stripCredentials((String) urlMethod.invoke(dataSource, (Object[])null)); } catch (Exception me){ return "<unknown> " + dataSource.getClass(); } } } }
/** * Determines through reflection the methods used for invoking the TestRunnerService. * * @throws Exception */ private void initializeServiceRunnerInvocationMethods() throws Exception { // get JUnit test service reference // this is a loose reference - update it if the JUnitTestActivator class is changed. BundleContext ctx = getRuntimeBundleContext(); ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE); Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE); service = ctx.getService(reference); Assert.notNull(service, "no service found for reference: " + reference); serviceTrigger = service.getClass().getDeclaredMethod("executeTest", new Class[0]); ReflectionUtils.makeAccessible(serviceTrigger); Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass()); }
private void injectServicesViaAnnotatedSetterMethods(final Object bean, final String beanName) { ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() { public void doWith(Method method) { ServiceReference s = AnnotationUtils.getAnnotation(method, ServiceReference.class); if (s != null && method.getParameterTypes().length == 1) { try { if (logger.isDebugEnabled()) logger.debug("Processing annotation [" + s + "] for [" + bean.getClass().getName() + "." + method.getName() + "()] on bean [" + beanName + "]"); method.invoke(bean, getServiceImporter(s, method, beanName).getObject()); } catch (Exception e) { throw new IllegalArgumentException("Error processing service annotation", e); } } } }); }
private static void setId(Class<?> clazz, Object instance, String fieldName, Object value) { try { Field field = ReflectionUtils.findField(clazz, fieldName); field.setAccessible(true); int modifiers = field.getModifiers(); Field modifierField = field.getClass().getDeclaredField("modifiers"); modifiers = modifiers & ~Modifier.FINAL; modifierField.setAccessible(true); modifierField.setInt(field, modifiers); ReflectionUtils.setField(field, instance, value); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); } }
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class<?> targetClass = AopUtils.getTargetClass(bean); ReflectionUtils.doWithMethods(targetClass, method -> { WxButton wxButton = AnnotationUtils.getAnnotation(method, WxButton.class); if (wxButton != null) { wxMenuManager.add(wxButton); } }); return bean; }
public static Object getFieldValue(Object instance, String fieldName) { try { return ReflectionUtils.findField(instance.getClass(), fieldName).get(instance); } catch (Exception e) { throw new Error(e); } }
public void mockReflectionUtils() { new MockUp<ReflectionUtils>() { @Mock Object getField(Field field, Object target) { Response response = Response.ok(200); return new CseClientHttpResponse(response); } }; }
/** * Create an instance of the specified job class. * <p>Can be overridden to post-process the job instance. * @param bundle the TriggerFiredBundle from which the JobDetail * and other info relating to the trigger firing can be obtained * @return the job instance * @throws Exception if job instantiation failed */ protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0... Method getJobDetail = bundle.getClass().getMethod("getJobDetail"); Object jobDetail = ReflectionUtils.invokeMethod(getJobDetail, bundle); Method getJobClass = jobDetail.getClass().getMethod("getJobClass"); Class<?> jobClass = (Class<?>) ReflectionUtils.invokeMethod(getJobClass, jobDetail); return jobClass.newInstance(); }
/** * Convert the given CORBA SystemException that happened during remote access * to Spring's RemoteAccessException if the method signature does not declare * RemoteException. Else, return the SystemException wrapped in a RemoteException. * @param method the invoked method * @param ex the RemoteException that happened * @return the exception to be thrown to the caller */ private Exception convertCorbaAccessException(SystemException ex, Method method) { if (ReflectionUtils.declaresException(method, RemoteException.class)) { // A traditional RMI service: wrap CORBA exceptions in standard RemoteExceptions. return new RemoteException("Failed to access CORBA service [" + getJndiName() + "]", ex); } else { if (isConnectFailure(ex)) { return new RemoteConnectFailureException("Could not connect to CORBA service [" + getJndiName() + "]", ex); } else { return new RemoteAccessException("Could not access CORBA service [" + getJndiName() + "]", ex); } } }
/** * Retrieve the Connection via JBoss' {@code getUnderlyingResultSet} method. */ @Override public ResultSet getNativeResultSet(ResultSet rs) throws SQLException { if (this.wrappedResultSetClass.isAssignableFrom(rs.getClass())) { return (ResultSet) ReflectionUtils.invokeJdbcMethod(this.getUnderlyingResultSetMethod, rs); } return rs; }
@Before public void init() { manager = new ExternalTaskManagerImpl(); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(ExternalTaskManagerImpl.class, "packages") , manager , Arrays.asList(Command.class.getPackage().getName()) ); }
@Test public void testToCommand() { manager.init(); LockedExternalTaskDto task = EnhancedRandom.random(LockedExternalTaskDto.class); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(LockedExternalTaskDto.class, "topicName") , task , Command.TASK_NAME ); String stringVar = "value"; String otherVar = "other value"; task.getVariables().put("stringVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(stringVar))); task.getVariables().put("otherVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(otherVar))); Object object = manager.toCommand(task); Assert.assertNotNull(object); Assert.assertTrue(object instanceof Command); Command command = (Command) object; Assert.assertEquals(stringVar, command.getStringVar()); Assert.assertEquals(otherVar, command.getAnotherStringVar()); ReflectionUtils.doWithFields(LockedExternalTaskDto.class, field -> { if (field.getName().equals("variables")) { return; } Field commandField = ReflectionUtils.findField(Command.class, field.getName()); Assert.assertNotNull("No field with name: " + field.getName(), commandField); Assert.assertEquals( JavaUtils.getFieldWithoutCheckedException(field, task) , JavaUtils.getFieldWithoutCheckedException(commandField, command) ); }); }
@Before public void init() throws IOException { Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn(JSON); Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.<Class<SimpleCommand>>any())).thenReturn(COMMAND); mapper = new JsonTaskMapper(); JavaUtils.setFieldWithoutCheckedException( ReflectionUtils.findField(JsonTaskMapper.class, "objectMapper") , mapper , objectMapper ); }
protected void setUp() throws Exception { Method m = ReflectionUtils.findMethod(Object.class, "hashCode"); context = new MockBundleContext(); interceptor = new LocalBundleContextAdvice(context); invocation = new MockMethodInvocation(m) { public Object proceed() throws Throwable { assertSame("bundle context not set", context, LocalBundleContext.getInvokerBundleContext()); return null; } }; }
/** * Builds a WebSphere JDBCConnectionSpec object for the current settings * and calls {@code WSDataSource.getConnection(JDBCConnectionSpec)}. * @see #createConnectionSpec * @see com.ibm.websphere.rsadapter.WSDataSource#getConnection(com.ibm.websphere.rsadapter.JDBCConnectionSpec) */ @Override protected Connection doGetConnection(String username, String password) throws SQLException { // Create JDBCConnectionSpec using current isolation level value and read-only flag. Object connSpec = createConnectionSpec( getCurrentIsolationLevel(), getCurrentReadOnlyFlag(), username, password); if (logger.isDebugEnabled()) { logger.debug("Obtaining JDBC Connection from WebSphere DataSource [" + getTargetDataSource() + "], using ConnectionSpec [" + connSpec + "]"); } // Create Connection through invoking WSDataSource.getConnection(JDBCConnectionSpec) return (Connection) ReflectionUtils.invokeJdbcMethod( this.wsDataSourceGetConnectionMethod, getTargetDataSource(), connSpec); }
/** * Instantiates a new Cookie retrieving cookie generator. * @param casCookieValueManager the cookie manager */ public CookieRetrievingCookieGenerator(final CookieValueManager casCookieValueManager) { super(); final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); if(setHttpOnlyMethod != null) { super.setCookieHttpOnly(true); } else { logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0."); } this.casCookieValueManager = casCookieValueManager; }
private Object convertDataArrayToTargetArray(Object[] array, Class<?> targetClass) throws NoSuchMethodException { Class<?> targetType = targetClass.getComponentType(); Method fromMethod = targetType.getMethod("from", array.getClass().getComponentType()); Object resultArray = Array.newInstance(targetType, array.length); for (int i = 0; i < array.length; i++) { Array.set(resultArray, i, ReflectionUtils.invokeMethod(fromMethod, null, array[i])); } return resultArray; }