28 Mayıs 2017 Pazar

SpringMVC WebApplicationContext Sınıfı

Giriş
ApplicationContext arayüzünü gerçekleştirir. Açıklaması şöyle
Interface to provide configuration for a web application.
Şeklen şöyle
Açıklaması şöyle
Sometimes circumstances do not allow you to completely switch to a different framework. The Spring Framework does not force you to use everything within it; it is not an all-or-nothing solution. Existing front-ends built with Struts, Tapestry, JSF or other UI frameworks can be integrated with a Spring- based middle-tier, which allows you to use Spring transaction features. You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.
Spring ile 3 çeşit WebApplication yapılabilir. Açıklaması şöyle
For REACTIVE , it will create AnnotationConfigReactiveWebServerApplicationContext
For SERVLET , it will create AnnotationConfigServletWebServerApplicationContext
For NONE, it will create AnnotationConfigApplicationContext

constructor
Spring tarafından yaratılmayan HttpServlet sınıfında erişmek için şöyle yaparız.
WebApplicationContext appContext = WebApplicationContextUtils
  .getWebApplicationContext(getServletContext());

6 Mayıs 2017 Cumartesi

SpringSecurity DelegatingFilterProxy Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.web.filter.DelegatingFilterProxy;
Açıklaması şöyle
This is a servlet filter embedded in the spring context. Its job is to delegate the incoming request to a bunch of filters (not managed as spring beans) provided by the Spring web framework and hence the name, DelegatingFilterProxy. 
Açıklaması şöyle
This is a filter implementation that takes a springbean name as init param and delegates the filter request to that bean.
Bu bean SecurityFilterAutoConfiguration tarafından yaratılır. SecurityFilterAutoConfiguration içindeki kod şöyle
@Bean
@ConditionalOnBean(name = DEFAULT_FILTER_NAME)
public DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(
SecurityProperties securityProperties) {
  
  DelegatingFilterProxyRegistrationBean registration =
new DelegatingFilterProxyRegistrationBean(DEFAULT_FILTER_NAME);
  registration.setOrder(securityProperties.getFilter().getOrder());
  registration.setDispatcherTypes(getDispatcherTypes(securityProperties));
  return registration;
}
Açıklaması şöyle
You’d notice that Spring boot autoconfigures a Bean of the type DelegatingFilterProxy via a filter registration class -> DelegatingFilterProxyRegistrationBean class. The bean is only created if another bean named -> springSecurityFilterChain is found in the classpath.
springSecurityFilterChain is an alias for the Spring Security’s FilterChainProxy class. It means this filter is optional and only created if we use spring security in our application.

You’d also notice that while creating this DelegatingFilterProxy Filter, we pass the springSecurityFilterChain name in its constructor. It is done, to set the delegation link between the two classes. DelegatingFilterProxy uses this delegation link during runtime to invoke spring security functionality.
Tanımlama
Şöyle yaparız.
<filter>
  <filter-name>myFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy
  </filter-class>
  <init-param>
    <param-name>targetBeanName</param-name>
    <param-value>myFilterBean<param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>myFilter</filter-name>
  <url-pattern>/myFilterPattern/*</url-pattern>
</filter-mapping>
Filtre şöyledir
public class MyFilter extends GenericFilterBean {

  @Autowired
  InjectedBean someInjectedBean;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
      chain.doFilter(request, response);
  }
}


5 Mayıs 2017 Cuma

SpringLDAP LdapTemplate Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.ldap.core.LdapTemplate;
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.springframework.ldap</groupId>
  <artifactId>spring-ldap-core</artifactId>
</dependency>
Tanımlama
Şöyle yaparız.
<ldap:context-source
    id="ldapContextSource"
    url="ldap://ldaphost:389"
    username="cn=ldaptestadmin,cn=Administrators,cn=config"
    password="abcxyz"
    base="dc=studentBase,dc=example,dc=com"/>

<ldap:ldap-template id="ldapTemplate" context-source-
    ref="ldapContextSource"/>
create metodu
Örnek ver

authenticate metodu
Örnek
Şöyle yaparız
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.filter.Filter;
import org.springframework.ldap.support.LdapUtils;

LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://localhost:8389/dc=springframework,dc=org");
contextSource.setAnonymousReadOnly(true);
contextSource.setUserDn("uid={0},ou=people");
contextSource.afterPropertiesSet();

LdapTemplate ldapTemplate = new LdapTemplate(contextSource);

Filter filter = new EqualsFilter("uid", "myname");
Boolean authenticated = ldapTemplate.authenticate(LdapUtils.emptyLdapName(),
filter.encode(), "mypassword");
if (authenticated) {
  ...
}
DefaultIncrementalAttributesMapper İle Kullanımı
Açıklaması şöyle
If you know the distinguished name (dn), you can use the DefaultIncrementAttributesMapper to look up for multi-valued attributes (eg. the mail attribute).
Örnek
Şöyle yaparız
@Service class LdapQueryService( private val ldapTemplate: LdapTemplate ) { private fun getMultiValuedAttributesWithDefaultIncrementAttributesMapper(dn: String, attr: String): List<String> { val attributes = DefaultIncrementalAttributesMapper.lookupAttributes(ldapTemplate, dn, attr) val results = ArrayList<String>() for (i in 0 until attributes.get(attr).size()) { results.add(attributes.get(attr)[i].toString()) } return results } fun query(): List<String> { val dn = "cn=Amanda,ou=Users" val attr = "mail" val emails = getMultiValuedAttributesWithDefaultIncrementAttributesMapper(dn, attr) return emails } }
search metodu - AttributesMapper
Açıklaması şöyle
Internally, LdapTemplate iterates over all entries found, calling the given AttributesMapper for each entry, and collects the results in a list. The list is then returned by the search method.
Örnek
Şöyle yaparız
@Service class LdapQueryService( private val ldapTemplate: LdapTemplate ) { fun queryWithAttributeMapper(userId: String): List<User> { return ldapTemplate.search("ou=Users", "uid=$userId", AttributesMapper { attributes -> val id = attributes.get("uid").get().toString() val name = attributes.get("displayname").get().toString() val emails = attributes.get("mail").all.toList() as List<String> User(userId = id, name = name, emails = emails) }) } }
search metodu - ContextMapper
Açıklaması şöyle
Whenever an entry is found in the LDAP tree, its attributes and Distinguished Name (DN) will be used by Spring LDAP to construct a DirContextAdapter. This enables us to use a ContextMapper to transform the found values.
Açıklaması şöyle
The advantage of the ContextMapper is that

- it handles NullPointerException by returning null instead of throwing exceptions.
- it simplifies attributes retrieval operations (especially for multi-value attributes) with getStringAttribute() and getStringAttributes() methods.
- it allows you to retrieve distinguished name (dn), schemas and object classes.
Örnek
Şöyle yaparız
@Service class LdapQueryService( private val ldapTemplate: LdapTemplate ) { fun queryWithContextMapper(userId: String): List<User> { return ldapTemplate.search("ou=Users", "uid=$userId", object: AbstractContextMapper<User>() { override fun doMapFromContext(ctx: DirContextOperations): AdUser { val dn = ctx.dn val id = ctx.getStringAttribute("uid") val name = ctx.getStringAttribute("displayname") val emails = ctx.getStringAttributes("mail").toList() return User(id, name, emails) } }) } }


CachingClientConnectionFactory Sınıfı

Giriş
Bu sınıf Spring Integration projesine dahil.

Tanımlama
Şöyle yaparız.
<!-- Pooled Connection factory -->
<int-ip:tcp-connection-factory id="client"
  type="client"
  host="${gateway.url}"
  port="${gateway.port}"
  single-use="true"
  so-timeout="${gateway.socket.timeout}"
  serializer="appSerializerDeserializer"
  deserializer="appSerializerDeserializer" />


<bean id="cachedClient"
  class="org.springframework.integration.ip.tcp.connection.
         CachingClientConnectionFactory">
    <constructor-arg ref="client" />
    <constructor-arg value="${gateway.pool.size}" />
</bean>