Java Code Examples for org.springframework.stereotype.Component

The following are top voted examples for showing how to use org.springframework.stereotype.Component. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tephra   File: ClassReloaderImpl.java   Source Code and License 8 votes vote down vote up
private String getBeanName(Class<?> clazz) {
    Component component = clazz.getAnnotation(Component.class);
    if (component != null)
        return component.value();

    Repository repository = clazz.getAnnotation(Repository.class);
    if (repository != null)
        return repository.value();

    Service service = clazz.getAnnotation(Service.class);
    if (service != null)
        return service.value();

    Controller controller = clazz.getAnnotation(Controller.class);
    if (controller != null)
        return controller.value();

    return null;
}
 
Example 2
Project: EasyFXML   File: PrivateConstructorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void assertExistsPrivateCtor() {
    reflections.getSubTypesOf(Object.class).stream()
        .filter(clazz -> !clazz.isAnnotationPresent(Configuration.class))
        .filter(clazz -> !clazz.isAnnotationPresent(Component.class))
        .filter(clazz -> !clazz.isAnnotationPresent(SpringBootApplication.class))
        .filter(clazz -> !clazz.getName().endsWith("Test"))
        .filter(clazz -> !clazz.isInterface())
        .filter(clazz ->
            Arrays.stream(clazz.getDeclaredFields())
                .allMatch(field -> Modifier.isStatic(field.getModifiers())))
        .forEach(clazz -> {
            System.out.println("Expecting class "+clazz.getName()+" to :");
            System.out.print("\t-> be final ");
            assertThat(clazz).isFinal();
            System.out.println("[*]");
            System.out.print("\t-> have exactly one constructor ");
            Constructor<?>[] constructors = clazz.getDeclaredConstructors();
            assertThat(constructors).hasSize(1);
            System.out.println("[*]");
            System.out.print("\t-> and that this constructor is private ");
            assertThat(Modifier.isPrivate(constructors[0].getModifiers()));
            System.out.println("[*]");
        });
}
 
Example 3
Project: spring-data-generator   File: ManagerStructure.java   Source Code and License 6 votes vote down vote up
public ManagerStructure(String managerPackage, String entityName, String postfix, String repositoryPackage, String repositoryPostfix) {

        String managerName = entityName + postfix;
        String repositoryName = entityName + repositoryPostfix;
        String repositoryNameAttribute = GeneratorUtils.decapitalize(repositoryName);

        this.objectBuilder = new ObjectBuilder(new ObjectStructure(managerPackage, ScopeValues.PUBLIC, ObjectTypeValues.CLASS, managerName)
                .addImport(repositoryPackage + "." + repositoryName)
                .addImport(Autowired.class)
                .addImport(Component.class)
                .addAnnotation(Component.class)
                .addAttribute(repositoryName, repositoryNameAttribute)
                .addConstructor(new ObjectStructure.ObjectConstructor(ScopeValues.PUBLIC, managerName)
                        .addAnnotation(Autowired.class)
                        .addArgument(repositoryName, repositoryNameAttribute)
                        .addBodyLine(ObjectValues.THIS.getValue() + repositoryNameAttribute + ExpressionValues.EQUAL.getValue() + repositoryNameAttribute)
                )
        ).setAttributeBottom(false);

    }
 
Example 4
Project: bdf2   File: AutoFormBuilder.java   Source Code and License 6 votes vote down vote up
public void build(Object control, ViewComponent parentViewComponent) {
	AutoForm autoForm = (AutoForm) control;
	String id = autoForm.getId();
	ViewComponent component = generateViewComponent(id,AutoForm.class);
	if (StringUtils.isEmpty(id)) {
		component.setEnabled(false);
	}
	parentViewComponent.addChildren(component);
	for (com.bstek.dorado.view.widget.Component c : autoForm.getElements()) {
		for (IControlBuilder builder : builders) {
			if (builder.support(c)) {
				builder.build(c, component);
				break;
			}
		}
	}
}
 
Example 5
Project: bdf2   File: ContainerBuilder.java   Source Code and License 6 votes vote down vote up
public void build(Object control, ViewComponent parentViewComponent) {
	Container container=(Container)control;
	String id=container.getId();
	ViewComponent component=new ViewComponent();
	component.setId(id);
	component.setIcon(">dorado/res/"+Container.class.getName().replaceAll("\\.", "/")+".png");
	component.setName(container.getClass().getSimpleName());
	if(StringUtils.isEmpty(id)){
		component.setEnabled(false);
	}
	parentViewComponent.addChildren(component);
	for(com.bstek.dorado.view.widget.Component c:container.getChildren()){
		for(IControlBuilder builder:builders){
			if(builder.support(c)){
				builder.build(c, component);
				break;
			}
		}
	}
}
 
Example 6
Project: bdf2   File: ContainerBuilder.java   Source Code and License 6 votes vote down vote up
public void build(Object control, ViewComponent parentViewComponent) {
	Container container=(Container)control;
	String id=container.getId();
	ViewComponent component=new ViewComponent();
	component.setId(id);
	component.setIcon(">dorado/res/"+container.getClass().getName().replaceAll("\\.", "/")+".png");
	component.setName(container.getClass().getSimpleName());
	if(StringUtils.isEmpty(id)){
		component.setEnabled(false);
	}
	parentViewComponent.addChildren(component);
	for(com.bstek.dorado.view.widget.Component c:container.getChildren()){
		for(IControlBuilder builder:builders){
			if(builder.support(c)){
				builder.build(c, component);
				break;
			}
		}
	}
}
 
Example 7
Project: spring4-understanding   File: GroovyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
// Test for SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
Example 8
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 6 votes vote down vote up
@Test
public void synthesizeAnnotationFromAnnotationAttributesWithoutAttributeAliases() throws Exception {

	// 1) Get an annotation
	Component component = WebController.class.getAnnotation(Component.class);
	assertNotNull(component);

	// 2) Convert the annotation into AnnotationAttributes
	AnnotationAttributes attributes = getAnnotationAttributes(WebController.class, component);
	assertNotNull(attributes);

	// 3) Synthesize the AnnotationAttributes back into an annotation
	Component synthesizedComponent = synthesizeAnnotation(attributes, Component.class, WebController.class);
	assertNotNull(synthesizedComponent);

	// 4) Verify that the original and synthesized annotations are equivalent
	assertNotSame(component, synthesizedComponent);
	assertEquals(component, synthesizedComponent);
	assertEquals("value from component: ", "webController", component.value());
	assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value());
}
 
Example 9
Project: spring4-understanding   File: AnnotationMetadataTests.java   Source Code and License 6 votes vote down vote up
private void doTestSubClassAnnotationInfo(AnnotationMetadata metadata) {
	assertThat(metadata.getClassName(), is(AnnotatedComponentSubClass.class.getName()));
	assertThat(metadata.isInterface(), is(false));
	assertThat(metadata.isAnnotation(), is(false));
	assertThat(metadata.isAbstract(), is(false));
	assertThat(metadata.isConcrete(), is(true));
	assertThat(metadata.hasSuperClass(), is(true));
	assertThat(metadata.getSuperClassName(), is(AnnotatedComponent.class.getName()));
	assertThat(metadata.getInterfaceNames().length, is(0));
	assertThat(metadata.isAnnotated(Component.class.getName()), is(false));
	assertThat(metadata.isAnnotated(Scope.class.getName()), is(false));
	assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false));
	assertThat(metadata.hasAnnotation(Component.class.getName()), is(false));
	assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false));
	assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false));
	assertThat(metadata.getAnnotationTypes().size(), is(0));
	assertThat(metadata.getAnnotationAttributes(Component.class.getName()), nullValue());
	assertThat(metadata.getAnnotatedMethods(DirectAnnotation.class.getName()).size(), equalTo(0));
	assertThat(metadata.isAnnotated(IsAnnotatedAnnotation.class.getName()), equalTo(false));
	assertThat(metadata.getAllAnnotationAttributes(DirectAnnotation.class.getName()), nullValue());
}
 
Example 10
Project: spring4-understanding   File: AnnotationMetadataTests.java   Source Code and License 6 votes vote down vote up
private void doTestMetadataForAnnotationClass(AnnotationMetadata metadata) {
	assertThat(metadata.getClassName(), is(Component.class.getName()));
	assertThat(metadata.isInterface(), is(true));
	assertThat(metadata.isAnnotation(), is(true));
	assertThat(metadata.isAbstract(), is(true));
	assertThat(metadata.isConcrete(), is(false));
	assertThat(metadata.hasSuperClass(), is(false));
	assertThat(metadata.getSuperClassName(), nullValue());
	assertThat(metadata.getInterfaceNames().length, is(1));
	assertThat(metadata.getInterfaceNames()[0], is(Annotation.class.getName()));
	assertThat(metadata.isAnnotated(Documented.class.getName()), is(false));
	assertThat(metadata.isAnnotated(Scope.class.getName()), is(false));
	assertThat(metadata.isAnnotated(SpecialAttr.class.getName()), is(false));
	assertThat(metadata.hasAnnotation(Documented.class.getName()), is(true));
	assertThat(metadata.hasAnnotation(Scope.class.getName()), is(false));
	assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(false));
	assertThat(metadata.getAnnotationTypes().size(), is(3));
}
 
Example 11
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: PropertyMappingContextCustomizer.java   Source Code and License 6 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {
	Class<?> beanClass = bean.getClass();
	Set<Class<?>> components = new LinkedHashSet<Class<?>>();
	Set<Class<?>> propertyMappings = new LinkedHashSet<Class<?>>();
	while (beanClass != null) {
		for (Annotation annotation : AnnotationUtils.getAnnotations(beanClass)) {
			if (isAnnotated(annotation, Component.class)) {
				components.add(annotation.annotationType());
			}
			if (isAnnotated(annotation, PropertyMapping.class)) {
				propertyMappings.add(annotation.annotationType());
			}
		}
		beanClass = beanClass.getSuperclass();
	}
	if (!components.isEmpty() && !propertyMappings.isEmpty()) {
		throw new IllegalStateException("The @PropertyMapping "
				+ getAnnotationsDescription(propertyMappings)
				+ " cannot be used in combination with the @Component "
				+ getAnnotationsDescription(components));
	}
	return bean;
}
 
Example 12
Project: singular-server   File: SingularServerSpringMockitoTestConfig.java   Source Code and License 6 votes vote down vote up
public void resetAndReconfigure(boolean debug) {
    SingularContextSetup.reset();
    ApplicationContextMock applicationContext = new ApplicationContextMock();
    ServiceRegistryLocator.setup(new SpringServiceRegistry());
    new ApplicationContextProvider().setApplicationContext(applicationContext);
    registerBeanFactories(applicationContext);
    registerAnnotated(applicationContext, Named.class);
    registerAnnotated(applicationContext, Service.class);
    registerAnnotated(applicationContext, Component.class);
    registerAnnotated(applicationContext, Repository.class);
    registerMockitoTestClassMocksAndSpies(applicationContext);
    getLogger().info("Contexto configurado com os beans: ");
    if (debug) {
        applicationContext.listAllBeans().forEach(
                b -> getLogger().info(b)
        );
    }
}
 
Example 13
Project: spring-boot-concourse   File: PropertyMappingContextCustomizer.java   Source Code and License 6 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
		throws BeansException {
	Class<?> beanClass = bean.getClass();
	Set<Class<?>> components = new LinkedHashSet<Class<?>>();
	Set<Class<?>> propertyMappings = new LinkedHashSet<Class<?>>();
	while (beanClass != null) {
		for (Annotation annotation : AnnotationUtils.getAnnotations(beanClass)) {
			if (isAnnotated(annotation, Component.class)) {
				components.add(annotation.annotationType());
			}
			if (isAnnotated(annotation, PropertyMapping.class)) {
				propertyMappings.add(annotation.annotationType());
			}
		}
		beanClass = beanClass.getSuperclass();
	}
	if (!components.isEmpty() && !propertyMappings.isEmpty()) {
		throw new IllegalStateException("The @PropertyMapping "
				+ getAnnotationsDescription(propertyMappings)
				+ " cannot be used in combination with the @Component "
				+ getAnnotationsDescription(components));
	}
	return bean;
}
 
Example 14
Project: moebooru-viewer   File: MoebooruViewer.java   Source Code and License 6 votes vote down vote up
public void showPostById(int id, java.awt.Component dialogParent){
    JOptionPane optionPane = new JOptionPane(Localization.format("retrieval_format", String.valueOf(id)), JOptionPane.INFORMATION_MESSAGE);
    JButton button = new JButton(Localization.getString("cancel"));
    optionPane.setOptions(new Object[]{button});
    JDialog dialog = optionPane.createDialog(dialogParent, Localization.getString("retrieving"));
    button.addActionListener(event -> dialog.dispose());
    dialog.setModalityType(ModalityType.MODELESS);
    dialog.setVisible(true);
    executor.execute(() -> {
        List<Post> searchPosts = mapi.listPosts(1, 1, "id:" + id);
        SwingUtilities.invokeLater(() -> {
            if (dialog.isDisplayable()){
                dialog.dispose();
                if (!searchPosts.isEmpty()){
                    showPostFrame.showPost(searchPosts.get(0));
                }else{
                    JOptionPane.showMessageDialog(null, Localization.getString("id_doesnot_exists"),
                        Localization.getString("error"), JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    });
}
 
Example 15
Project: mybatis-spring-1.2.2   File: MapperScannerConfigurerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMarkerInterfaceAndAnnotationScan() {
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "markerInterface", MapperInterface.class);
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "annotationClass", Component.class);

  startContext();

  // everything should be loaded but the marker interface
  applicationContext.getBean("annotatedMapper");
  applicationContext.getBean("mapperSubinterface");
  applicationContext.getBean("mapperChildInterface");

  assertBeanNotLoaded("mapperInterface");
}
 
Example 16
Project: zstack   File: ConfigurationManagerImpl.java   Source Code and License 6 votes vote down vote up
private void generateApiMessageGroovyClass(StringBuilder sb, List<String> basePkgs) {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.addIncludeFilter(new AssignableTypeFilter(APIMessage.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIReply.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(APIEvent.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                //classToApiMessageGroovyClass(sb, clazz);
                classToApiMessageGroovyInformation(sb, clazz);
            } catch (ClassNotFoundException e) {
                logger.warn(String.format("Unable to generate groovy class for %s", bd.getBeanClassName()), e);
            }
        }
    }
}
 
Example 17
Project: zstack   File: ConfigurationManagerImpl.java   Source Code and License 6 votes vote down vote up
private void generateInventoryPythonClass(StringBuilder sb, List<String> basePkgs) {
    List<String> inventoryPython = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(PythonClassInventory.class));
    scanner.addExcludeFilter(new AnnotationTypeFilter(Component.class));
    for (String pkg : basePkgs) {
        for (BeanDefinition bd : scanner.findCandidateComponents(pkg).stream().sorted((bd1, bd2) -> {
            return bd1.getBeanClassName().compareTo(bd2.getBeanClassName());
        }).collect(Collectors.toList())) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                if (isPythonClassGenerated(clazz)) {
                    /* This class was generated as other's parent class */
                    continue;
                }
                inventoryPython.add(classToInventoryPythonClass(clazz));
            } catch (Exception e) {
                logger.warn(String.format("Unable to generate python class for %s", bd.getBeanClassName()), e);
            }
        }
    }

    for (String invstr : inventoryPython) {
        sb.append(invstr);
    }
}
 
Example 18
Project: spring-dynamic   File: Commons.java   Source Code and License 6 votes vote down vote up
public static String getBeanName(Class<?> beanClass) {
	String beanName = null;
	Named nameAnn = beanClass.getAnnotation(Named.class);
	//todo 如果没有named标注,则不加入bean;
	if (nameAnn != null) {
		if (Utils.hasLength(nameAnn.value()))
			beanName = nameAnn.value();
	}
	else {
		Component componentAnn = beanClass.getAnnotation(Component.class);
		if (componentAnn != null) {
			if (Utils.hasLength(componentAnn.value()))
				beanName = componentAnn.value();
		}
	}
	
	if (!Utils.hasLength(beanName)) {
		beanName = Utils.beanName(beanClass.getSimpleName());
	}
	return beanName;
}
 
Example 19
Project: swing   File: StyleProfilePanel.java   Source Code and License 6 votes vote down vote up
private void decorateLabelWithHighestValue(JPanel panel) {
    JLabel labelWithHigestValue = new JLabel("0.0");
    for (java.awt.Component component : panel.getComponents()) {
        if (component instanceof JLabel) {
            JLabel label = (JLabel) component;
            try {
                double value = Double.parseDouble(label.getText());
                if (value > Double.parseDouble(labelWithHigestValue.getText())) {
                    labelWithHigestValue = label;
                }
            } catch (NumberFormatException ignore) {}
        }
    }
    labelWithHigestValue.setOpaque(true);
    labelWithHigestValue.setBackground(Color.lightGray);
}
 
Example 20
Project: swing   File: EntityList.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public java.awt.Component getListCellRendererComponent(JList list,
                                                       Object value,
                                                       int index,
                                                       boolean isSelected,
                                                       boolean cellHasFocus) {
    E entity = (E) entityListModel.getElementAt(index);
    if (entity != null && entity.toString() != null && !entity.toString().isEmpty()) {
        setText(entity.toString());
    } else {
        setText("");
    }
    if (entityIcon != null) {
        setIcon(entityIcon);
    }
    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }
    return this;
}
 
Example 21
Project: swing   File: ReturnsSummaryTable.java   Source Code and License 6 votes vote down vote up
public java.awt.Component getTableCellRendererComponent(JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
    if (isSelected) {
        setForeground(table.getSelectionForeground());
        setBackground(table.getSelectionBackground());
    } else {
        setForeground(table.getForeground());
        setBackground(table.getBackground());
    }
    if (row == table.getSelectedRow() && column == table.getSelectedColumn()) {
        setBorder(selectedBorder);       
    } else {
        setBorder(defaultBorder);
    }
    setText((value == null) ? "" : value.toString());
    return this;
}
 
Example 22
Project: swing   File: ReturnsSummaryTable.java   Source Code and License 6 votes vote down vote up
@Override
public java.awt.Component getTableCellRendererComponent(JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
    String text = value.toString();
    setText(text + " ");
    if (isSelected) {
        setBackground(table.getSelectionBackground());
        setForeground(table.getSelectionForeground());
    } else {
        setBackground(table.getBackground());
        setForeground(table.getForeground());
    }
    return this;
}
 
Example 23
Project: swing   File: BenchmarkPortfolioStatisticsTable.java   Source Code and License 6 votes vote down vote up
@Override
public java.awt.Component getTableCellRendererComponent(JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
    setForeground(Color.black);
    String category = (String) value;
    setText(category);
    if (categories.contains(category) || category.isEmpty()) {
        setBackground(Colors.tableRowColor);
    } else {
        setBackground(Color.white);
    }
    if (isSelected) {
        setBackground(Colors.navy);
        setForeground(Color.white);
    }
    return this;
}
 
Example 24
Project: swing   File: StockTable.java   Source Code and License 6 votes vote down vote up
@Override
public java.awt.Component getTableCellRendererComponent(JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
    String text = value.toString();
    try {
        Double.parseDouble(text);
        setHorizontalAlignment(JLabel.RIGHT);
        setText(text + " ");
    } catch (NumberFormatException e) {
        setHorizontalAlignment(JLabel.LEFT);
        setText(text);
    }
    if (isSelected) {
        setBackground(table.getSelectionBackground());
        setForeground(table.getSelectionForeground());
    } else {
        setBackground(table.getBackground());
        setForeground(table.getForeground());
    }
    return this;
}
 
Example 25
Project: swing   File: RegimeComboBox.java   Source Code and License 6 votes vote down vote up
@Override
public java.awt.Component getListCellRendererComponent(JList list,
                                                             Object value,
                                                             int index,
                                                             boolean isSelected,
                                                             boolean cellHasFocus) {
          Regime regime = (Regime) value;
          setText(regime.getName());
          if (isSelected) {
              setBackground(list.getSelectionBackground());
              setForeground(list.getSelectionForeground());
          } else {
              setBackground(list.getBackground());
              setForeground(list.getForeground());
          }
          return this;
      }
 
Example 26
Project: SocialDataImporter   File: ClassUtilTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for {@link ch.sdi.core.util.ClassUtil#findCandidatesByAnnotation(java.lang.Class, java.lang.String)}.
 */
@Test
public void testFindCandidatesByAnnotationAndType()
{
    myLog.debug( "we parse all classes which are below the top level package" );
    String pack = this.getClass().getPackage().getName();
    myLog.debug( "found package: " + pack );
    pack = pack.replace( '.', '/' );
    String root = pack.split( "/" )[0];

    Collection<? extends Class<?>> received = ClassUtil.findCandidatesByAnnotation( ConverterFactory.class,
                                                                                    Component.class,
                                                                                    root );

    Assert.assertNotNull( received );
    Assert.assertEquals( 1, received.size() );
    received.forEach( c -> myLog.debug( "Found class with annotation @Component and type 'ConverterFactory': "
                + c.getName() ) );

}
 
Example 27
Project: class-guard   File: GroovyScriptFactoryTests.java   Source Code and License 6 votes vote down vote up
@Test
// Test for SPR-6268
public void testRefreshableFromTagProxyTargetClass() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd-proxy-target-class.xml",
			getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals("Hello World!", messenger.getMessage());

	assertTrue(ctx.getBeansOfType(ConcreteMessenger.class).values().contains(messenger));

	// Check that AnnotationUtils works with concrete proxied script classes
	assertNotNull(AnnotationUtils.findAnnotation(messenger.getClass(), Component.class));
}
 
Example 28
Project: mybatis-spring   File: MapperScannerConfigurerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMarkerInterfaceAndAnnotationScan() {
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "markerInterface", MapperInterface.class);
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "annotationClass", Component.class);

  startContext();

  // everything should be loaded but the marker interface
  applicationContext.getBean("annotatedMapper");
  applicationContext.getBean("mapperSubinterface");
  applicationContext.getBean("mapperChildInterface");

  assertBeanNotLoaded("mapperInterface");
}
 
Example 29
Project: super-csv-annotation   File: SpringBeanFactory.java   Source Code and License 6 votes vote down vote up
private String getBeanName(final Class<?> clazz) {
    
    final Component componentAnno = clazz.getAnnotation(Component.class);
    if(componentAnno != null && !componentAnno.value().isEmpty()) {
        return componentAnno.value();
    }
    
    final Service serviceAnno = clazz.getAnnotation(Service.class);
    if(serviceAnno != null && !serviceAnno.value().isEmpty()) {
        return serviceAnno.value();
    }
    
    final Repository repositoryAnno = clazz.getAnnotation(Repository.class);
    if(repositoryAnno != null && !repositoryAnno.value().isEmpty()) {
        return repositoryAnno.value();
    }
    
    final Controller controllerAnno = clazz.getAnnotation(Controller.class);
    if(controllerAnno != null && !controllerAnno.value().isEmpty()) {
        return controllerAnno.value();
    }
    
    // ステレオタイプのアノテーションでBean名の指定がない場合は、クラス名の先頭を小文字にした名称とする。
    return uncapitalize(clazz.getSimpleName());
}
 
Example 30
Project: parkingfriends   File: SpringReloader.java   Source Code and License 6 votes vote down vote up
private Annotation getSpringClassAnnotation(Class clazz) {
    Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class);

    if (classAnnotation == null) {
        classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class);
    }
    if (classAnnotation == null) {
        classAnnotation = AnnotationUtils.findAnnotation(clazz, RestController.class);
    }
    if (classAnnotation == null) {
        classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class);
    }
    if (classAnnotation == null) {
        classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class);
    }

    return classAnnotation;
}
 
Example 31
Project: terminal-recall   File: GamepadInputDeviceServiceFactory.java   Source Code and License 6 votes vote down vote up
GamepadInputDevice(Controller controller){
if(controller==null)
    throw new NullPointerException("Passed Controller intolerably null.");
this.controller = controller;
controller.setEventQueueSize(256);
eventQueue = controller.getEventQueue();
System.out.println("CONTROLLER: "+controller.getClass().getName());
controllerSources = new ArrayList<GamepadControllerSource>(controller.getComponents().length);
//System.out.println("Rumblers: "+controller.getRumblers().length);
//controller.getRumblers()[0].rumble(1f);
for(net.java.games.input.Component comp : controller.getComponents()){
    GamepadControllerSource gcs = new GamepadControllerSource(comp);
    controllerSources.add(gcs);
    controllerSourceMap.put(comp, gcs);
    nameMap.put(comp.getName(),gcs);
    System.out.println("Component found: "+comp.getName());
}//end for(components)
gamepadEventThread.start();
   }
 
Example 32
Project: poi-visualizer   File: POITopMenuBar.java   Source Code and License 5 votes vote down vote up
private void editApply() {
	java.awt.Component comp = contentArea.getSelectedComponent();
	if (comp instanceof CodeArea) {
		treeObservable.setBinarySource(() -> {
			// workaround bug in ByteArrayDataInputStream.read(byte[] output, int off, int len)
			final BinaryData bad = ((CodeArea)comp).getData();
			final long size = bad.getDataSize();
			ByteArrayEditableData data = new ByteArrayEditableData();
			try (InputStream is = new BoundedInputStream(bad.getDataInputStream(),size)) {
				data.loadFromStream(is);
			}
			return data;
		});
	} else if (comp instanceof XMLEditor) {
		((XMLEditor)comp).saveXml();
	} else {
		return;
	}
	treeObservable.notifyObservers(MENU_EDIT_APPLY);	
}
 
Example 33
Project: springboot-addon   File: RestNewEndpointDecorator.java   Source Code and License 5 votes vote down vote up
public static JavaClassSource createGreetingPropertiesClass(JavaClassSource current) {
   JavaClassSource source = Roaster.create(JavaClassSource.class).setName("GreetingProperties").setPackage(current.getPackage());
   source.addAnnotation(Component.class);
   source.addAnnotation(ConfigurationProperties.class).setStringValue("greeting");
   source.addProperty(String.class, "message").getField().setStringInitializer("Hello, %s!");
   return source;
}
 
Example 34
Project: homunculus   File: SPRComponentWidget.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public <T> AnnotatedComponent<T> process(Scope scope, Class<T> clazz) {
    Component widget = clazz.getAnnotation(Component.class);
    if (widget != null) {
        return new AnnotatedComponent(clazz, widget.value(), ComponentType.BEAN);
    }
    return null;
}
 
Example 35
Project: bdf2   File: AutoFormBuilder.java   Source Code and License 5 votes vote down vote up
public void build(Object control, ViewComponent parentViewComponent) {
	AutoForm autoForm = (AutoForm) control;
	String id = autoForm.getId();
	ViewComponent component = generateViewComponent(id,AutoForm.class);
	if (StringUtils.isEmpty(id)) {
		component.setEnabled(false);
	}
	parentViewComponent.addChildren(component);
	for (com.bstek.dorado.view.widget.Component c : autoForm.getElements()) {
		for (IControlBuilder builder : builders) {
			if (builder.support(c)) {
				builder.build(c, component);
				break;
			}
		}
	}
}
 
Example 36
Project: dwr   File: DwrClassPathBeanDefinitionScanner.java   Source Code and License 5 votes vote down vote up
public DwrClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry)
{
    super(registry, false);
    addExcludeFilter(new AnnotationTypeFilter(Component.class));
    addExcludeFilter(new AnnotationTypeFilter(Service.class));
    addExcludeFilter(new AnnotationTypeFilter(Repository.class));
    addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    setScopedProxyMode(ScopedProxyMode.INTERFACES);
}
 
Example 37
Project: spring4-understanding   File: ClassPathScanningCandidateComponentProviderTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testWithComponentAnnotationOnly() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Service.class));
	provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertEquals(2, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertFalse(containsBeanClass(candidates, FooServiceImpl.class));
	assertFalse(containsBeanClass(candidates, StubFooDao.class));
	assertFalse(containsBeanClass(candidates, NamedStubDao.class));
}
 
Example 38
Project: spring4-understanding   File: ClassPathScanningCandidateComponentProviderTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testWithMultipleMatchingFilters() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
	provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertEquals(6, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertTrue(containsBeanClass(candidates, FooServiceImpl.class));
}
 
Example 39
Project: spring4-understanding   File: ClassPathScanningCandidateComponentProviderTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testExcludeTakesPrecedence() {
	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
	provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
	provider.addIncludeFilter(new AssignableTypeFilter(FooServiceImpl.class));
	provider.addExcludeFilter(new AssignableTypeFilter(FooService.class));
	Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
	assertEquals(5, candidates.size());
	assertTrue(containsBeanClass(candidates, NamedComponent.class));
	assertTrue(containsBeanClass(candidates, ServiceInvocationCounter.class));
	assertFalse(containsBeanClass(candidates, FooServiceImpl.class));
}
 
Example 40
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/** @since 4.2 */
@Test
public void findMethodAnnotationWithMetaMetaAnnotationOnLeaf() throws Exception {
	Method m = Leaf.class.getMethod("metaMetaAnnotatedOnLeaf");
	assertNull(m.getAnnotation(Component.class));
	assertNull(getAnnotation(m, Component.class));
	assertNotNull(findAnnotation(m, Component.class));
}
 
Example 41
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/** @since 4.1.2 */
@Test
public void findClassAnnotationFavorsMoreLocallyDeclaredComposedAnnotationsOverAnnotationsOnInterfaces() {
	Component component = findAnnotation(ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class,
		Component.class);
	assertNotNull(component);
	assertEquals("meta2", component.value());
}
 
Example 42
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/** @since 4.0.3 */
@Test
public void findClassAnnotationFavorsMoreLocallyDeclaredComposedAnnotationsOverInheritedComposedAnnotations() {
	Component component = findAnnotation(SubSubClassWithInheritedMetaAnnotation.class, Component.class);
	assertNotNull(component);
	assertEquals("meta2", component.value());
}
 
Example 43
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
public void getAnnotationAttributesWithoutAttributeAliases() {
	Component component = WebController.class.getAnnotation(Component.class);
	assertNotNull(component);

	AnnotationAttributes attributes = (AnnotationAttributes) getAnnotationAttributes(component);
	assertNotNull(attributes);
	assertEquals("value attribute: ", "webController", attributes.getString(VALUE));
	assertEquals(Component.class, attributes.annotationType());
}
 
Example 44
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
public void synthesizeAnnotationWithoutAttributeAliases() throws Exception {
	Component component = WebController.class.getAnnotation(Component.class);
	assertNotNull(component);
	Component synthesizedComponent = synthesizeAnnotation(component);
	assertNotNull(synthesizedComponent);
	assertSame(component, synthesizedComponent);
	assertEquals("value attribute: ", "webController", synthesizedComponent.value());
}
 
Example 45
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
public void synthesizeAnnotationFromMapWithoutAttributeAliases() throws Exception {
	Component component = WebController.class.getAnnotation(Component.class);
	assertNotNull(component);

	Map<String, Object> map = Collections.singletonMap(VALUE, "webController");
	Component synthesizedComponent = synthesizeAnnotation(map, Component.class, WebController.class);
	assertNotNull(synthesizedComponent);

	assertNotSame(component, synthesizedComponent);
	assertEquals("value from component: ", "webController", component.value());
	assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value());
}
 
Example 46
Project: spring4-understanding   File: AnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
public void synthesizeAnnotationFromMapWithAttributeOfIncorrectType() throws Exception {
	Map<String, Object> map = Collections.singletonMap(VALUE, 42L);

	exception.expect(IllegalArgumentException.class);
	exception.expectMessage(startsWith("Attributes map"));
	exception.expectMessage(containsString("returned a value of type [java.lang.Long]"));
	exception.expectMessage(containsString("for attribute [value]"));
	exception.expectMessage(containsString("but a value of type [java.lang.String] is required"));
	exception.expectMessage(containsString("as defined by annotation type [" + Component.class.getName() + "]"));
	synthesizeAnnotation(map, Component.class, null);
}
 
Example 47
Project: spring4-understanding   File: AnnotationTypeFilterTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testNonAnnotatedClassDoesntMatch() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	String classUnderTest = "org.springframework.core.type.AnnotationTypeFilterTests$SomeNonCandidateClass";
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest);

	AnnotationTypeFilter filter = new AnnotationTypeFilter(Component.class);
	assertFalse(filter.match(metadataReader, metadataReaderFactory));
	ClassloadingAssertions.assertClassNotLoaded(classUnderTest);
}
 
Example 48
Project: spring4-understanding   File: AnnotationMetadataTests.java   Source Code and License 5 votes vote down vote up
@Test
public void asmAnnotationMetadataForAnnotation() throws Exception {
	MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(Component.class.getName());
	AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
	doTestMetadataForAnnotationClass(metadata);
}
 
Example 49
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
private void assertAtComponentOnComposedAnnotation(Class<?> startClass, Class<?> rootDeclaringClass,
		Class<?> declaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
	AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(startClass, Component.class);
	assertNotNull("AnnotationDescriptor should not be null", descriptor);
	assertEquals("rootDeclaringClass", rootDeclaringClass, descriptor.getRootDeclaringClass());
	assertEquals("declaringClass", declaringClass, descriptor.getDeclaringClass());
	assertEquals("annotationType", Component.class, descriptor.getAnnotationType());
	assertEquals("component name", name, descriptor.getAnnotation().value());
	assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation());
	assertEquals("composedAnnotationType", composedAnnotationType, descriptor.getComposedAnnotationType());
}
 
Example 50
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Class<?> startClass,
		Class<?> rootDeclaringClass, Class<?> declaringClass, String name,
		Class<? extends Annotation> composedAnnotationType) {
	Class<Component> annotationType = Component.class;
	UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class,
		annotationType, Order.class, Transactional.class);
	assertNotNull("UntypedAnnotationDescriptor should not be null", descriptor);
	assertEquals("rootDeclaringClass", rootDeclaringClass, descriptor.getRootDeclaringClass());
	assertEquals("declaringClass", declaringClass, descriptor.getDeclaringClass());
	assertEquals("annotationType", annotationType, descriptor.getAnnotationType());
	assertEquals("component name", name, ((Component) descriptor.getAnnotation()).value());
	assertNotNull("composedAnnotation should not be null", descriptor.getComposedAnnotation());
	assertEquals("composedAnnotationType", composedAnnotationType, descriptor.getComposedAnnotationType());
}
 
Example 51
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
public void findAnnotationDescriptorWithLocalAndMetaComponentAnnotation() throws Exception {
	Class<Component> annotationType = Component.class;
	AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(HasLocalAndMetaComponentAnnotation.class,
		annotationType);
	assertEquals(HasLocalAndMetaComponentAnnotation.class, descriptor.getRootDeclaringClass());
	assertEquals(annotationType, descriptor.getAnnotationType());
	assertNull(descriptor.getComposedAnnotation());
	assertNull(descriptor.getComposedAnnotationType());
}
 
Example 52
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.0.3
 */
@Test
public void findAnnotationDescriptorOnAnnotatedClassWithMissingTargetMetaAnnotation() {
	// InheritedAnnotationClass is NOT annotated or meta-annotated with @Component
	AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(InheritedAnnotationClass.class,
		Component.class);
	assertNull("Should not find @Component on InheritedAnnotationClass", descriptor);
}
 
Example 53
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.0.3
 */
@Test
public void findAnnotationDescriptorOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
	AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(MetaCycleAnnotatedClass.class,
		Component.class);
	assertNull("Should not find @Component on MetaCycleAnnotatedClass", descriptor);
}
 
Example 54
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void findAnnotationDescriptorForTypesWithLocalAndMetaComponentAnnotation() throws Exception {
	Class<Component> annotationType = Component.class;
	UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
		HasLocalAndMetaComponentAnnotation.class, Transactional.class, annotationType, Order.class);
	assertEquals(HasLocalAndMetaComponentAnnotation.class, descriptor.getRootDeclaringClass());
	assertEquals(annotationType, descriptor.getAnnotationType());
	assertNull(descriptor.getComposedAnnotation());
	assertNull(descriptor.getComposedAnnotationType());
}
 
Example 55
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.0.3
 */
@Test
@SuppressWarnings("unchecked")
public void findAnnotationDescriptorForTypesOnAnnotatedClassWithMissingTargetMetaAnnotation() {
	// InheritedAnnotationClass is NOT annotated or meta-annotated with @Component,
	// @Service, or @Order, but it is annotated with @Transactional.
	UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(InheritedAnnotationClass.class,
		Service.class, Component.class, Order.class);
	assertNull("Should not find @Component on InheritedAnnotationClass", descriptor);
}
 
Example 56
Project: spring4-understanding   File: MetaAnnotationUtilsTests.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.0.3
 */
@Test
@SuppressWarnings("unchecked")
public void findAnnotationDescriptorForTypesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
	UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(MetaCycleAnnotatedClass.class,
		Service.class, Component.class, Order.class);
	assertNull("Should not find @Component on MetaCycleAnnotatedClass", descriptor);
}
 
Example 57
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: BeanDefinitionLoader.java   Source Code and License 5 votes vote down vote up
private boolean isComponent(Class<?> type) {
	// This has to be a bit of a guess. The only way to be sure that this type is
	// eligible is to make a bean definition out of it and try to instantiate it.
	if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
		return true;
	}
	// Nested anonymous classes are not eligible for registration, nor are groovy
	// closures
	if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
			|| type.getConstructors() == null || type.getConstructors().length == 0) {
		return false;
	}
	return true;
}
 
Example 58
Project: spring-boot-concourse   File: BeanDefinitionLoader.java   Source Code and License 5 votes vote down vote up
private boolean isComponent(Class<?> type) {
	// This has to be a bit of a guess. The only way to be sure that this type is
	// eligible is to make a bean definition out of it and try to instantiate it.
	if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
		return true;
	}
	// Nested anonymous classes are not eligible for registration, nor are groovy
	// closures
	if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
			|| type.getConstructors() == null || type.getConstructors().length == 0) {
		return false;
	}
	return true;
}
 
Example 59
Project: mybatis-spring-1.2.2   File: MapperScannerConfigurerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAnnotationScan() {
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "annotationClass", Component.class);

  startContext();

  // only annotated mappers should be loaded
  applicationContext.getBean("annotatedMapper");
  applicationContext.getBean("mapperChildInterface");

  assertBeanNotLoaded("mapperInterface");
  assertBeanNotLoaded("mapperSubinterface");
}
 
Example 60
Project: contestparser   File: BeanDefinitionLoader.java   Source Code and License 5 votes vote down vote up
private boolean isComponent(Class<?> type) {
	// This has to be a bit of a guess. The only way to be sure that this type is
	// eligible is to make a bean definition out of it and try to instantiate it.
	if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
		return true;
	}
	// Nested anonymous classes are not eligible for registration, nor are groovy
	// closures
	if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
			|| type.getConstructors() == null || type.getConstructors().length == 0) {
		return false;
	}
	return true;
}