private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationFeature) { objectMapper.configure((SerializationFeature) feature, enabled); } else if (feature instanceof DeserializationFeature) { objectMapper.configure((DeserializationFeature) feature, enabled); } else if (feature instanceof MapperFeature) { objectMapper.configure((MapperFeature) feature, enabled); } else { throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); } }
@Override protected ApplicationContext createApplicationContext(String uri) throws MalformedURLException { Resource resource = Utils.resourceFromString(uri); LOG.debug("Using " + resource + " from " + uri); try { return new ResourceXmlApplicationContext(resource) { @Override protected ConfigurableEnvironment createEnvironment() { return new ReversePropertySourcesStandardServletEnvironment(); } @Override protected void initPropertySources() { WebApplicationContextUtils.initServletPropertySources(getEnvironment().getPropertySources(), ServletContextHolder.getServletContext()); } }; } catch (FatalBeanException errorToLog) { LOG.error("Failed to load: " + resource + ", reason: " + errorToLog.getLocalizedMessage(), errorToLog); throw errorToLog; } }
@Override public void release() throws FatalBeanException { synchronized (bfgInstancesByKey) { BeanFactory savedRef = this.groupContextRef; if (savedRef != null) { this.groupContextRef = null; BeanFactoryGroup bfg = bfgInstancesByObj.get(savedRef); if (bfg != null) { bfg.refCount--; if (bfg.refCount == 0) { destroyDefinition(savedRef, resourceLocation); bfgInstancesByKey.remove(resourceLocation); bfgInstancesByObj.remove(savedRef); } } else { // This should be impossible. logger.warn("Tried to release a SingletonBeanFactoryLocator group definition " + "more times than it has actually been used. Resource name [" + resourceLocation + "]"); } } } }
private void configureFeature(Object feature, boolean enabled) { if (feature instanceof JsonParser.Feature) { this.objectMapper.configure((JsonParser.Feature) feature, enabled); } else if (feature instanceof JsonGenerator.Feature) { this.objectMapper.configure((JsonGenerator.Feature) feature, enabled); } else if (feature instanceof SerializationFeature) { this.objectMapper.configure((SerializationFeature) feature, enabled); } else if (feature instanceof DeserializationFeature) { this.objectMapper.configure((DeserializationFeature) feature, enabled); } else if (feature instanceof MapperFeature) { this.objectMapper.configure((MapperFeature) feature, enabled); } else { throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName()); } }
/** * Is called by the Spring container after all properties have been set. <br> * It is implemented in order to initialize the beanClass field correctly and to make sure * that either the bean id or the bean itself have been set on this creator. * @see org.springframework.beans.factory.InitializingBean */ public void afterPropertiesSet() { // make sure that either the bean or the beanId have been set correctly if (bean != null) { this.beanClass = bean.getClass(); } else if (beanId != null) { this.beanClass = applicationContext.getType(beanId); } else { throw new FatalBeanException( "You should either set the bean property directly or set the beanId property"); } // make sure to handle cglib proxies correctly if(AopUtils.isCglibProxyClass(this.beanClass)) { this.beanClass = this.beanClass.getSuperclass(); } }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String prefix = (String) attribute(metadata, "prefix"); Class<?> value = (Class<?>) attribute(metadata, "value"); ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment(); try { new Binder(ConfigurationPropertySources.from(environment.getPropertySources())) .bind(prefix, Bindable.of(value)) .orElseThrow( () -> new FatalBeanException("Could not bind DataSourceSettings properties")); return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix)); } catch (Exception e) { //ignore } return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix)); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { try { Class<?> wrapped = AopUtils.getTargetClass(bean); if (!isSpring(wrapped)) { Class<?> declaring = AnnotationUtils.findAnnotationDeclaringClass(Steps.class, wrapped); if (null != declaring) { processStepsBean(beanName, wrapped); } } return bean; } catch (Exception e) { throw new FatalBeanException("unable to processAnnotationContainer @Steps beans", e); } }
/** * Is called by the Spring container after all properties have been set. <br> * It is implemented in order to initialize the beanClass field correctly and to make sure * that either the bean id or the bean itself have been set on this creator. * @see org.springframework.beans.factory.InitializingBean */ public void afterPropertiesSet() { // make sure that either the bean or the beanId have been set correctly if (bean != null) { this.beanClass = bean.getClass(); } else if (beanId != null) { this.beanClass = beanFactory.getType(beanId); } else { throw new FatalBeanException("You should either set the bean property directly or set the beanId property"); } // make sure to handle cglib proxies correctly if (ClassUtils.isCglibProxyClass(this.beanClass)) { this.beanClass = this.beanClass.getSuperclass(); } }
/** * Tries to obtain the beanClassName from the definition and if that fails tries to get it from * the parent (and even parent BeanFactory if we have to). * * @param definition a non null instance * @param registry a non null instance * @return class name or null if not found */ protected String resolveBeanClassname(BeanDefinition definition, BeanDefinitionRegistry registry) { String beanClassName = definition.getBeanClassName(); while(!StringUtils.hasText(beanClassName)) { try { Method m = definition.getClass().getMethod("getParentName", new Class[0]); String parentName = (String) m.invoke(definition, new Object[0]); BeanDefinition parentDefinition = findParentDefinition(parentName, registry); beanClassName = parentDefinition.getBeanClassName(); definition = parentDefinition; } catch (Exception e) { throw new FatalBeanException("No parent bean could be found for " + definition, e); } } return beanClassName; }
@Test public void handlerBeanNotFound() throws Exception { MockServletContext sc = new MockServletContext(""); XmlWebApplicationContext root = new XmlWebApplicationContext(); root.setServletContext(sc); root.setConfigLocations(new String[] {"/org/springframework/web/servlet/handler/map1.xml"}); root.refresh(); XmlWebApplicationContext wac = new XmlWebApplicationContext(); wac.setParent(root); wac.setServletContext(sc); wac.setNamespace("map2err"); wac.setConfigLocations(new String[] {"/org/springframework/web/servlet/handler/map2err.xml"}); try { wac.refresh(); fail("Should have thrown NoSuchBeanDefinitionException"); } catch (FatalBeanException ex) { NoSuchBeanDefinitionException nestedEx = (NoSuchBeanDefinitionException) ex.getCause(); assertEquals("mainControlle", nestedEx.getBeanName()); } }
private void validateDeclaredRemotingException(Method method, Class<?> clazz) throws IllegalStateException { Class<?>[] exceptionTypeArray = method.getExceptionTypes(); boolean located = false; for (int i = 0; i < exceptionTypeArray.length; i++) { Class<?> exceptionType = exceptionTypeArray[i]; if (RemotingException.class.isAssignableFrom(exceptionType)) { located = true; break; } } if (located) { throw new FatalBeanException(String.format( "The method(%s) shouldn't be declared to throw a remote exception: org.bytesoft.compensable.RemotingException!", method)); } }
@Override protected void processBeanDefinition(ConfigurableListableBeanFactory beanFactory, BeanDefinition bd, String beanClassName, String definitionName) throws FatalBeanException { if (beanFactory instanceof DefaultListableBeanFactory) { DefaultListableBeanFactory factory = (DefaultListableBeanFactory) beanFactory; try { final WebScript webScript = AnnotationUtils.findAnnotation(Class.forName(beanClassName), WebScript.class); if (webScript != null) { String beanName = webScript.value(); if (StringUtils.hasText(beanName)) { final String webScriptName = "webscript." + beanName + "." + webScript.method().toString().toLowerCase(); factory.removeBeanDefinition(definitionName); factory.registerBeanDefinition(webScriptName, bd); } else { throw new FatalBeanException(String.format("%s is @WebScript annotated, but no value set.", beanClassName)); } } } catch (ClassNotFoundException e) { logger.warn(String.format("ClassNotFoundException while searching for ChildOf annotation on bean name '%s' of type '%s'. This error is expected on Alfresco Community 4.2.c. for some classes in package 'org.alfresco.repo'", definitionName, beanClassName)); } } else { logger.error(String.format("Unable to register '%s' as webscript because beanFactory is not instance of 'DefaultListableBeanFactory'", definitionName)); } }
@Override protected void processBeanDefinition(ConfigurableListableBeanFactory beanFactory, BeanDefinition bd, String beanClassName, String definitionName) throws FatalBeanException { try { final ChildOf childOf = AnnotationUtils.findAnnotation(Class.forName(beanClassName), ChildOf.class); if (childOf != null) { final String parentName = childOf.value(); if (StringUtils.hasText(parentName)) { bd.setParentName(parentName); } else { throw new FatalBeanException(String.format("%s is @ChildOf annotated, but no value set.", beanClassName)); } } } catch (ClassNotFoundException e) { logger.warn(String.format("ClassNotFoundException while searching for ChildOf annotation on bean name '%s' of type '%s'. This error is expected on Alfresco Community 4.2.c. for some classes in package 'org.alfresco.repo'", definitionName, beanClassName)); } }
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames(); for (String definitionName : beanDefinitionNames) { try { final BeanDefinition bd = beanFactory.getBeanDefinition(definitionName); final String beanClassName = bd.getBeanClassName(); if (StringUtils.hasText(beanClassName)) { try { processBeanDefinition(beanFactory, bd, beanClassName, definitionName); } catch (Exception e) { logger.error(e.getMessage(), e); throw new FatalBeanException("Unknown class defined.", e); } } } catch (NoSuchBeanDefinitionException ex) { logger.warn(ex.getMessage()); continue; } } }
/** * Create a new MergeClassPathXMLApplicationContext, loading the definitions from the given definitions. Note, * all sourceLocation files will be merged using standard Spring configuration override rules. However, the patch * files are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according * to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any * further id attributes. * * @param sourceLocations array of relative (or absolute) paths within the class path for the source application context files * @param patchLocations array of relative (or absolute) paths within the class path for the patch application context files * @param parent the parent context * @throws BeansException */ public MergeClassPathXMLApplicationContext(String[] sourceLocations, String[] patchLocations, ApplicationContext parent) throws BeansException { this(parent); ResourceInputStream[] sources = new ResourceInputStream[sourceLocations.length]; for (int j=0;j<sourceLocations.length;j++){ sources[j] = new ResourceInputStream(getClassLoader(parent).getResourceAsStream(sourceLocations[j]), sourceLocations[j]); } ResourceInputStream[] patches = new ResourceInputStream[patchLocations.length]; for (int j=0;j<patches.length;j++){ patches[j] = new ResourceInputStream(getClassLoader(parent).getResourceAsStream(patchLocations[j]), patchLocations[j]); } ImportProcessor importProcessor = new ImportProcessor(this); try { sources = importProcessor.extract(sources); patches = importProcessor.extract(patches); } catch (MergeException e) { throw new FatalBeanException("Unable to merge source and patch locations", e); } this.configResources = new MergeApplicationContextXmlConfigResource().getConfigResources(sources, patches); refresh(); }
/** * JAVADOC Method Level Comments */ @Test public void testThrowsBindExceptionAndHeaders() { Foo u1 = new Foo(); when(validator.validate(u1, Default.class, Create.class)) .thenReturn(Collections.<ConstraintViolation<Foo>>emptySet()); doThrow(new FatalBeanException("Oops")).when(conversionService) .convert(any(CsvlineWrapper.class), eq(Object.class)); try { rowProcessor.processRow("Foo", new String[] { "name", "value" }, new String[] { "Username", "BRYAN" }, 1); fail("Should throw bind exception"); } catch (BindException be) { // force a parse error, results in a bind exception assertEquals("loader.parseError", be.getAllErrors().get(0).getCode()); } }
public static void loadFromFile(Path filePath) { try( BufferedReader reader = new BufferedReader(new FileReader(filePath.toString()))) { String line; while ((line = reader.readLine()) != null) { if (line.length() > 0) { String[] tokens = line.split(":", 3); map.put(tokens[0], new RedisInstance(tokens[1], tokens[2])); } } } catch( IOException ex){ Logging.writeLine("Error while reading file %s", filePath); Logging.logException(ex); throw new FatalBeanException(ex.getMessage()); } }
public static void LogError(Exception ex) { if (ex instanceof JedisConnectionException) { Throwable cause = ex.getCause(); if (cause != null && cause instanceof SocketTimeoutException) Logging.write("T"); else Logging.write("C"); } else if (ex instanceof JedisBusyException) { Logging.write("B"); } else if (ex instanceof JedisException) { Logging.write("E"); } else if (ex instanceof IOException){ Logging.write("C"); } else { Logging.logException(ex); throw new FatalBeanException(ex.getMessage(), ex); // unexpected exception type, so abort test for investigation } }
private NodeInfo buildStructDefNodeInfo(String structDefId) throws Exception { XdmAtomicValue structDefIdValue = new XdmAtomicValue(structDefId); XdmNode structDefNode = null; for (XdmDocument profileDoc : this.profileDocs) { if ((structDefNode = this.structDefXpathExec .load(new DynamicXpathOptionsImpl().setContextItem(profileDoc.getUnderlyingNode()).addVariable(ID_XPATH_VAR_QNAME, structDefIdValue)) .evaluateNode()) != null) { break; } } if (structDefNode == null) { throw new FatalBeanException(String.format("Unable to find %s StructureDefinition (id=%s) XML node.", this.specType.name(), structDefId)); } return structDefNode.getUnderlyingNode(); }
@Override @SuppressWarnings({ CompilerWarnings.UNCHECKED }) public void afterPropertiesSet() throws Exception { String id, name, path; for (U metadata : this.metadataItems) { id = metadata.getId(); name = metadata.getName(); path = metadata.getPath(); try { this.metadatas.put(path, this.buildMetadata(id, path, metadata)); this.beanMetadatas.put(((Class<? extends T>) metadata.getBeanImplClass()), metadata); LOGGER.debug(String.format("Built %s resource type (id=%s, name=%s, path=%s) metadata (params=[%s]).", this.specType, id, name, path, metadata.getParamMetadatas().values().stream().map(NamedBean::getName).collect(Collectors.joining(", ")))); } catch (Exception e) { throw new FatalBeanException( String.format("Unable to build %s resource type (id=%s, name=%s, path=%s) metadata.", this.specType, id, name, path), e); } } }
@Override public void onRefresh(Configuration configuration) throws BeansException { super.onRefresh(configuration); if (!useDNS()) { return; } SingletonBeanRegistry br = configuration.getBeanFactory(); try { br.registerSingleton("DNSMap", getDnsMap()); br.registerSingleton("NICUsage", getNicUsage()); br.registerSingleton("SelfLocator", getSelfLocator()); } catch (ConfigException e) { throw new FatalBeanException("ApplicationInformation initialization failed", e); } }
private HierarchicalContext lookupAnnotatedTargetContext(Object object, String annotatedTargetContextLevel) { HierarchicalContext targetContext = currentContext().contextOfBean( annotatedTargetContextLevel); if (targetContext == null) { throw new FatalBeanException( "no bean named " + annotatedTargetContextLevel + " defined in @" + TargetContextLevelOf.class.getSimpleName() + " in " + object.getClass() + " was found in any parent context. " + object.getClass() + " has to be created in a sub context of the context containing " + annotatedTargetContextLevel); } return targetContext; }
public void release() throws FatalBeanException { synchronized (bfgInstancesByKey) { BeanFactory savedRef = this.groupContextRef; if (savedRef != null) { this.groupContextRef = null; BeanFactoryGroup bfg = bfgInstancesByObj.get(savedRef); if (bfg != null) { bfg.refCount--; if (bfg.refCount == 0) { destroyDefinition(savedRef, resourceLocation); bfgInstancesByKey.remove(resourceLocation); bfgInstancesByObj.remove(savedRef); } } else { // This should be impossible. logger.warn("Tried to release a SingletonBeanFactoryLocator group definition " + "more times than it has actually been used. Resource name [" + resourceLocation + "]"); } } } }
@Test public void testCustomEditorConfigurerWithUnresolvableEditor() throws ParseException { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CustomEditorConfigurer cec = new CustomEditorConfigurer(); Map<String, String> editors = new HashMap<String, String>(); editors.put(Date.class.getName(), "MyNonExistingEditor"); editors.put("MyNonExistingType", "MyNonExistingEditor"); cec.setCustomEditors(editors); try { cec.postProcessBeanFactory(bf); fail("Should have thrown FatalBeanException"); } catch (FatalBeanException ex) { assertTrue(ex.getCause() instanceof ClassNotFoundException); } }
@Override public Object postProcessAfterInitialization(final Object bean, final String beanName) { if (bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof SecurityContextHolderAwareRequestFilter) { SecurityContextHolderAwareRequestFilter filter = (SecurityContextHolderAwareRequestFilter) bean; filter.setRolePrefix(StringUtils.EMPTY); try { filter.afterPropertiesSet(); } catch (ServletException e) { throw new FatalBeanException(e.getMessage(), e); } } return bean; }
@SuppressWarnings("unchecked") @Override public <T> T resolveSettings(Class<T> settingsClass, String prefix, ConfigurableEnvironment environment) { try { T newSettings = (T) Class.forName(settingsClass.getName()).newInstance(); PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(newSettings); factory.setTargetName(prefix); factory.setPropertySources(environment.getPropertySources()); factory.setConversionService(environment.getConversionService()); factory.bindPropertiesToTarget(); return newSettings; } catch (Exception ex) { throw new FatalBeanException("Could not bind DataSourceSettings properties", ex); } }
private Object createNewCollection(Object wrappedCollection) { if (wrappedConcreteType.isArray()) return Array.newInstance(wrappedConcreteType.getComponentType(), bufferedListModel.size()); Object newCollection; if (SortedSet.class.isAssignableFrom(wrappedConcreteType) && wrappedCollection instanceof SortedSet && ((SortedSet)wrappedCollection).comparator() != null) { try { Constructor con = wrappedConcreteType.getConstructor(new Class[] {Comparator.class}); newCollection = BeanUtils.instantiateClass(con, new Object[] {((SortedSet)wrappedCollection).comparator()}); } catch (NoSuchMethodException e) { throw new FatalBeanException("Could not instantiate SortedSet class [" + wrappedConcreteType.getName() + "]: no constructor taking Comparator found", e); } } else { newCollection = BeanUtils.instantiateClass(wrappedConcreteType); } return newCollection; }
/** * Creates a {@code ModuleHolder} from the specified {@code xml}. * * @param xml * the XML to load the {@code ModuleHolder} from */ protected void setModulesHolder(final String xml) { final InputStream res = getClass().getResourceAsStream(xml); if (modulesHolder != null) { modulesHolder.release(); } try { modulesHolder = configuration.loadDelayed("tidaXsltModelLoader", res); } catch (final FatalBeanException e) { final RuntimeException innerE = SpringHelper .getNoneSpringBeanException(e, RuntimeException.class); if (innerE == null) { throw e; } else { throw innerE; } } }
/** * @see org.springframework.beans.factory.config.BeanPostProcessor * #postProcessBeforeInitialization(java.lang.Object, java.lang.String) */ @SuppressWarnings("unchecked") public final Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { try { Class<T> lClass = getLifeCycleInterface(); if (lClass.isInstance(bean)) { // Check if the bean is registered in the context. // If not it was created by the container and so there // is no need to execute the callback. if (factory.containsBeanDefinition(name)) { executeLifecycleMethodBeforeInit((T) bean, name); } } } catch (Exception e) { throw new FatalBeanException("Unable to execute lifecycle method on bean" + name, e); } return bean; }
/** * @see org.springframework.beans.factory.config.BeanPostProcessor * #postProcessAfterInitialization(java.lang.Object, java.lang.String) */ @SuppressWarnings("unchecked") public final Object postProcessAfterInitialization(Object bean, String name) throws BeansException { try { Class<T> lClass = getLifeCycleInterface(); if (lClass.isInstance(bean)) { // Check if the bean is registered in the context. // If not it was created by the container and so there is no // need to execute the callback. if (factory.containsBeanDefinition(name)) { executeLifecycleMethodAfterInit((T) bean, name); } } } catch (Exception e) { throw new FatalBeanException("Unable to execute lifecycle method on bean" + name, e); } return bean; }
/** {@inheritDoc} */ @Override protected BasicJWKCredential doCreateInstance() throws Exception { if (jwkResource == null) { log.error("{}: No JWK credential provided", getConfigDescription()); throw new BeanCreationException("No JWK credential provided"); } JWK jwk = null; BasicJWKCredential jwkCredential = null; try (InputStream is = jwkResource.getInputStream()) { jwk = JWK.parse(new String(ByteStreams.toByteArray(is))); jwkCredential = new BasicJWKCredential(); if (jwk.getKeyType() == KeyType.EC || jwk.getKeyType() == KeyType.RSA) { if (jwk.isPrivate()) { jwkCredential.setPrivateKey(((AssymetricJWK) jwk).toPrivateKey()); } jwkCredential.setPublicKey(((AssymetricJWK) jwk).toPublicKey()); } else if (jwk.getKeyType() == KeyType.OCT) { jwkCredential.setSecretKey(((OctetSequenceKey) jwk).toSecretKey()); } else { throw new FatalBeanException("Unsupported KeyFile at " + jwkResource.getDescription()); } } catch (IOException | ParseException | JOSEException e) { log.error("{}: Could not decode KeyFile at {}: {}", getConfigDescription(), jwkResource.getDescription(), e); throw new FatalBeanException("Could not decode provided KeyFile " + jwkResource.getDescription(), e); } jwkCredential.setUsageType(getUsageType(jwk)); jwkCredential.setEntityId(getEntityID()); jwkCredential.setAlgorithm(jwk.getAlgorithm()); jwkCredential.setKid(jwk.getKeyID()); final List<String> keyNames = getKeyNames(); if (keyNames != null) { jwkCredential.getKeyNames().addAll(keyNames); } return jwkCredential; }
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { MutablePropertyValues newprops = new MutablePropertyValues(pvs); for (PropertyDescriptor pd : pds) { ServiceReference s = hasServiceProperty(pd); if (s != null && !pvs.contains(pd.getName())) { try { if (logger.isDebugEnabled()) logger.debug("Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]"); FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName); // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are // satisfied before stageTwo() is run. if (bean instanceof BeanPostProcessor) { ImporterCallAdapter.setCardinality(importer, Availability.OPTIONAL); } newprops.addPropertyValue(pd.getName(), importer.getObject()); } catch (Exception e) { throw new FatalBeanException("Could not create service reference", e); } } } return newprops; }