wtorek, 4 kwietnia 2017

Angular2 - Two ways of injecting dependencies

There are two ways of delivering dependencies to the created object. One is the widely know "injection by type", which is done by specifying typed parameters in constructor.

Inject by Type

constructor(private service: MyService) {
}
This assumes MyService is imported specific class put into providers of your module.

Inject by Name

Another way is "injecting by name".

constructor(@Inject('myService') private service) {
}
This time we required the following in the module providers list
{provide: 'myService', useClass: MyService},
The main advantage of the latter is we actually get rid of importing specific class, though, decouple from other local resources

We can also provide values instead of classes:

{provide: 'url', useValue: 'http://localhost'},

wtorek, 28 marca 2017

Angular2 - How to read params out of the current url

Lets say we want to take `id` param out of the current url. To do so we need to obtain current route by injecting "ActivatedRoute" object and read its params.
    constructor(private _route: ActivatedRoute){
        this.id = _route.params.map(param => param.id);
    }
The `id` field will be of Observable type.

wtorek, 31 stycznia 2017

Spring Security quick dive

To make authentication we need AuthenticationManager instance to call authenticate method on it passing Authentication object. There are couple classes that implement Authentication interface. AbstractAuthenticationToken - an abstract class AnonymousAuthenticationToken UsernamePasswordAuthenticationToken JaasAuthenticationToken RememberMeAuthenticationToken RunAsUserToken TestingAuthenticationToken PreAuthenticatedAuthenticationToken When we'd got authentication token we can validate it against registered AuthenticationProviders (eg. DaoAuthenticationProvider). What is interesting that when we'd got number of providers first one wins (only if returns null as a result authentication is fallbacked to the next provider).

poniedziałek, 30 stycznia 2017

How Spring look for bean definitions?

Scanning for beans

ConfigurationClassBeanDefinitionReader -> loadBeanDefinitionsForConfigurationClass

Constructor Resolver

autowireConstructor(beanName) Method responsible for finding out default parameters. AutoConfigurationPackages @AutoCondifurationPackage annotation user for registering

BeanDefinitionLoader

Four definition reader used. * AnnotationBeanDefintionReader * XmlBeanDefinitionReader * GroovyBeanDefinitionReader * ClassPathBeanDefinitionScanner

Scanning for bean definitions

Where: ClassPathScanningCandidateComponentProvider.java:265 public Set findCandidateComponents(String basePackage) 1. Constructs "search path" (e.g. "classpath*:org.example.services/*.class") 2. Takes all resources matching "search path" 3. If resource is readable it gathers it instantiate MetadataReader which basically is a facade for accessing class metadata such as annotations. 4. Next there is check against Exclude and Include filters. Exclude takes precedence. If class not match against includeFilter it is rejected.

Registering default filters

During creating SpringApplication "Include" filter always contains "Component" annotation type filter. Additionally both "javax.annotation.ManagedBean" (JSR-250) and "javax.inject.Named" (JST-330) are added if appropriate classes found on classpath.

środa, 11 stycznia 2017

Hibernate 5 schema validation internals

SchemaManagementToolCoordinator The static 'process' method takes 'metadata', 'serviceRegistry', 'properties' and 'delayedDropRegistry'. Based on 'properties' values the 'actions' are retrieved. SchemaValidatorImpl doValidation method takes Metadata and ExecutionOptions as a parameters.

poniedziałek, 14 listopada 2016

Java - stop reading possibly huge xml once given element found

  Path versionFile = installationPath.resolve("large.xml");

  SAXParserFactory factory = SAXParserFactory.newInstance();
  SAXParser parser = factory.newSAXParser();

  InputStream is = openStream(versionFile);

  class BreakException extends SAXException {
   private String value = null;
   private static final long serialVersionUID = 1L;
  }

  try {
   parser.parse(is, new DefaultHandler() {
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
     if ("InstallType".equals(qName)) {
      String value = attributes.getValue("currentVersion");
      // really dirty way to break sax parsing on demand and return value out of anonymous handle by the way ;)
      BreakException breakException = new BreakException();
      breakException.value = value;
      throw breakException;
     }
    }
   });
  } catch (BreakException be) {
   return be.value;
  }

piątek, 19 sierpnia 2016

Ratpack And Spring Getting Started

git

Maven dependendencies

        
            io.ratpack
            ratpack-core
            1.3.3
        

Spring initialization

@Configuration
@Profile(WEB_CONSOLE)
public class WebConsoleConfiguration {

    @Bean
    public ServerConfigBuilder webServerConfig() {
        ServerConfigBuilder embedded = ServerConfig.embedded();
        embedded.sysProps();
        return embedded;
    }

    @Bean
    public RatpackServer webServer(ServerConfigBuilder config) throws Exception {
        RatpackServer server = RatpackServer.of(b -> b
                .serverConfig(config)
                .registryOf(r -> r.add(String.class, "world"))
                .handlers(chain -> chain
                        .get("hello", ctx -> {
                            ctx.render(ctx.get(String.class) + " !");
                        })
                        .get("metrics", ctx -> {
                            ctx.render("Ooo..");
                        })
                )
        );
        server.start();
        return server;
    }

}