Archive for July, 2012

23
Jul

Removal of the branch from SVN

Posted by eugene as SVN

As you know, when removing a branch from SVN from any client, in my situation it’s Eclipse+Subclipse, the whole history of the branch is saved. And the only possibility to remove the history is to use the svdadmin + svndumpfilter utility.

Before all it’s necessary to create a full dump of repository. It’s not easy to do so but very easy:

svnadmin dump [path to the repository] > [file name]
svnadmin dump C:/MyRepository > MyRepository.dump

As the result of implementation of this command the text file will be created with the full content of repository.

Now it’s necessary to remove the obsolete branch from this file. Let’s apply the svndumpfilter utility for this:

svndumpfilter --drop-empty-revs [branch prefix] < [full dump file] > [file of the filtered dump]
svndumpfilter --drop-empty-revs test < MyRepository.dump > MyRepository.filtered

This command filtered the branches which names are started with ‘test’ and it created the MyRepository.filtered file where this branch is absent.

Now you can safely delete the repository C:/MyRepository folder (of course, save all the settings and hooks at first) and re-create the repository again:

svnadmin creat [path to the repository]
svnadmin create C:/MyRepository

Now you can load the filtered dump in the re-established repository:

svnadmin load [path to the repository] < [dump file]
svnadmin load C:/MyRepository < MyRepository.filtered

And that is all. Good luck.

23
Jul

PHP and FileReference in Flex

Posted by eugene as Flex, PHP

Authentication is necessary in any RIA application. Good it’s that making it is easy. The most common authentication is carried out on the server side and its results are recorded into the session parameters. It allows the user to request the authorization data only once for the entire work session with the application.

In conjunction of Flex and PHP, such a scheme works without any problem. All requests on the server side can be protected by authorization data in the PHP session. But if you try to check the authentication in the POST request of the file load handler from FileReference, it won’t work out. The session will be empty in the request handler.

The PHP session is getting connected with the browser session ID which is stored in the browser cookies. The problem is that when you request via FileReference cookies are not transmitted. As a result, PHP opens a new session.

To let PHP use an existing session, it is necessary to add the ID parameter to the current session. For example:

public function browse():void
{
	fileReference = new FileReference();
	fileReference.addEventListener(Event.SELECT, onDocumentSelected);
	fileReference.browse();
}
 
private function onDocumentSelected(event:Event):void
{
	getSession();
}
 
private function sessionRecieved(sessionId:String):void
{
	var url:String = "http://example.com?PHPSESSID=" + sessionId;
	var urlRequest:URLRequest = new URLRequest(url);
	fileReference.upload(urlRequest);
}

In the example, in the document selection handler the getSession() method is called which is requesting the session identifier from the PHP side. When the ID is received, the sessionReceived method is called which places the session IDs into the query line and initiates the file download. The session identifier is placed into the PHPSESSID parameter.

Also the identifier of the PHP session can be requested via JavaScript. But I do not like this option.

17
Jul

Removal of various diacritical characters from a string

Posted by eugene as Java

Got a problem – how to replace characters of national encoding in a string with the corresponding Latin ones.

For example, how to get explication from the explicación string.

package com.blogspot.atamanenko;
 
import java.text.Normalizer;
import java.text.Normalizer.Form;
 
public class StringNormalizer {
 
    public static String normalize(String string) {
        return Normalizer.normalize(string, Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
    }
}

Calling of Normalizer.normalize get the normalization of the input string. The subsequent call of the regular expression removes all the diacritical symbols received after the normalization.

17
Jul

A bit about the virtual methods in Java

Posted by eugene as Java

Today I want to look through the following features of re-defining of methods in Java. You cannot re-define the following in Java:

  • class fields
  • constructors, class initializers
  • Static methods
  • Static fields

You can read about it in Java Language Specification, §8.4.8 in more details.

So, all the non-static non-private (i.e. protected, package and public) methods are virtual. The ‘final’ keyword bans the possibility of the further re-defining of the method in the sub-classes. Let’s review the following example:

public class A {
     int i = 3;
     int getI() {return i;}
}
 
public class B extends A{
     int i = 5;
     int getI() {return i;}
}
 
A a = new B();
System.out.println(a.i);
System.out.println(a.getI());

Question: what will this code return?

Answer:

1. As the class fields are not inherited, then class A has its own i field and class B has the i field. As polymorphism is not actual for the fields, then when getting to a.i we are getting to the A class, that’s why 3 will be shown on the screen.

When calling the a.get() method, polymorphism should be used here, that’s why the method will be called from the class which instance has been created. Consequently, we’ll receive 5.

Another example:

public class A {
     static int i = 3;
     static int getI() {return i;}
}
 
public class B extends A{
     static int i = 5;
     static int getI() {return i;}
}
 
A a = new B();
System.out.println(a.i);
System.out.println(a.getI());

Static fields and methods are not virtual, that’s why both calls will return us 3.

17
Jul

A bit of magics from AspectJ

Posted by eugene as Spring Framework

Probably you’ve already coped with such a concept as AOP – aspect-oriented programming.

Usually they recall it when say about the use of declarative transactions, about verifying of access rights or about the realization of logging.

But these are not the only areas of AOP use.

I want to show yet couple of areas of using from the real projects:

  • Modification of the source code for realization of the additional opportunities.
  • Compulsory check of the contract between the modules.

Modification of the source code for realization of the additional opportunities

Let’s suppose that you have a module in the application which represents the necessary functionality. Everything is alright with the module except the one – all its methods can throw the verifying exceptions that leads to deterioration of the code readability as instead of the simple method calling:

service.doUsefulThing();

our call turns into

try {
        service.doUsefulThing();
    } catch ( FirstServiceException e) {
        processException(e);
    } catch ( SecondServiceException e) {
        processException(e);
    }

An additional problem is that the amount of 10+ modules in the module is as huge that it leads to the case that the try/catch blocks throw the code. The resolvoing with using of the Callback pattern also will lead to the code throwing.

Resolving the problem with the using of AOP

Resolving of this problem was the following – what if using the opportunities of AOP you’ll transform the verifying exception into non-verifying? So, we could avoid of the boring verification on the exceptions in our code, and for processing the exceptions (as we’ll always process it simulteneously) it’ll be enough to use processing of the exception on the upper level of abstraction.

For more elegant resolvation it’s decided to add our own annotation with the help of which it’s necessary to mark the method which uses the service from the ‘bad’ module.

package com.blogger.atamanenko;
 
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
 
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Inherited
public @interface SuppressExceptions {
}

And also the aspect which would have done all the necessary functionality for us:

public aspect ExceptionSupressingAspect {
 
        declare soft :ServiceException:  execution(@com.blogger.atamanenko.annotation.SuppressExceptions * *.*(..));
 
}

This aspect gives exactly the following: ‘Mitigates’ the ServiceExceptionexception exception for the method which is marked by the @SuppressExceptions annotation.

The example of using:

@SuppressExceptions
    protected Entity findEntity(final Identifiable id) {
        return entityService.findById(id);
    }

Compulsory check of the contract between the modules

Often we should forcibly require the implementation of some architectural restrictions, for example, the controllers should work only with the services and it’s restricted for them to directly request to the database.

For implementation of such verifications you can also use the opportunities of AOP.

Let’s suppose that the service module in our application pulls DTO outside for work, hiding the classes of the model by the time. In order to obviously ban the access to the classes and methods of the model we should create an aspect which would have call the compilation error while breaching the restriction.

aspect ForbidAccessToModelAspect {
 
//      Full prohibition of access to model:
        pointcut accessModel(): call(* com.blogger.atamanenko.app.model..*.*(..));
        declare error: accessModel() : "Illegal call to model";
 
}

After declaring such an aspect we’ll get the compilation error that would obviously lead to implementation of the architectural restriction.

If you need to allow access to the package from the other one, then we can modify our aspect by the following way:

aspect ForbidAccessToModelAspect2 {
 
        pointcut accessModel(): call(* com.blogger.atamanenko.app.model.**.*(..));
 
        // Allow access to model from specific package for methods and constructors
        pointcut allowAccessModelFromSpecificPackage(): withincode(* com.blogger.atamanenko.app.allowedpackage..*.*(..));
        pointcut allowAccessModelFromSpecificPackage2(): withincode(com.blogger.atamanenko.app.allowedpackage..*.new(..));
 
        // forbid usage from any other methods.
        declare error: accessModel() && !(allowAccessModelFromSpecificPackage() || allowAccessModelFromSpecificPackage()):"Illegal call to Model from forbidden package";
 
}

Such aspect which is created in our module will restrict us to use the classes of the model from all the packages except of com.blogger.atamanenko.app.allowedpackage.

Application assembly

Aspect file should be put into the src/main/aspect floder and for application assembly it’s necessary to use AspectJ compiler and not the standard Oracle Java Compiler.

The example of the configuration for Apache Maven:

    org.codehaus.mojo
    aspectj-maven-plugin
    ${aspectj-maven-plugin.version}
 
        1.6
 
 
                org.springframework
                spring-aspects
 
 
        true
 
 
 
process-sources
 
                compile
                test-compile

Conclusion

That is all. I deliberately did not start describing the aspects of the language constructs as they are described in the Aspect guide in details.

17
Jul

Using of BeanPostProcessor on the example of logging

Posted by eugene as Spring Framework

Today I want to tell you how to make the initialization of the logger in the class with the using of annotations and BeanPostProcessor. Very often we initialize the logger as follows:

public class MyClass {
    private static final Logger LOG = LoggerFactory.getLogger(MyClass.class);
}

I’ll show how to make so that you’ll be able to do the following:

@Log
private Logger LOG;

First of all you should declare the annotation:

@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface Log {
    String category() default "";
}

Secondly you should write your own BeanPostProcessor which would have set the logger for us:

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
 
@Component
public class LoggerPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }
 
    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) {
        ReflectionUtils.doWithFields(bean.getClass(), new FieldProcessor(bean, beanName), new LoggerFieldFilter());
        return bean;
    }
 
    private static class FieldProcessor implements ReflectionUtils.FieldCallback {
        private final Object bean;
        private final String beanName;
 
        private FieldProcessor(Object bean, String beanName) {
            this.bean = bean;
            this.beanName = beanName;
        }
 
        @Override
        public void doWith(Field field) throws IllegalAccessException {
            Log loggerAnnot = field.getAnnotation(Log.class);
 
            // Sanity check if annotation is on the field with correct type.
            if (field.getType().equals(org.slf4j.Logger.class)) {
                // As user can override logger category - check if it was done.
                String loggerCategory = loggerAnnot.category();
                if (StringUtils.isBlank(loggerCategory)) {
                    // use default category instead.
                    loggerCategory = bean.getClass().getName();
                }
                Logger logger = LoggerFactory.getLogger(loggerCategory);
                ReflectionUtils.makeAccessible(field);
                field.set(bean, logger);
            } else {
                throw new IllegalArgumentException(
                    "Unable to set logger on field '" + field.getName() + "' in bean '" + beanName +
                        "': field should have class " + Logger.class.getName());
            }
        }
    }
 
    private static class LoggerFieldFilter implements ReflectionUtils.FieldFilter {
        @Override
        public boolean matches(Field field) {
            Log logger = field.getAnnotation(Log.class);
            return null != logger;
        }
    }
}

If you use log4j or commons-logging, not sfl4j, then you should a bit rectify the code inside the doWith method. On the way this code shows the example of using the org.springframework.util.ReflectionUtils class.

16
Jul

Searching with the help of Spring Data JPA

Posted by eugene as Spring Data

Let us review one of the most useful things in Spring Data JPA – generating of JPQL queries based on the method name. Spring Data JPA is able to automatically generate requests using the method name for hint. For example, the User.findByLoginAndPassword method will generate approximately the following code:

FROM User u where u.login = :login and password = :password

Generally Spring Data JPA is trying to be smart so the implementation of the findBy{…} methods looks as follows:

  • At first you should look the @Query annotation on the method declaring, if it exists then it’s being used.
  • Then you should look the @NamedQuery annotation with the name like Entity.findMethodNme, in the above case it will be User.findByLoginAndPassword.
  • If you haven’t found anything then the request is generated due to method signature.

@Query contains the following benefits:

  • Allows not to clutter up the annotation of the domain entity.
  • Greatly helps if there’re implicit joins in the request because Spring Data JPA cannot correctly generate the SELECT COUNT(*) request which is necessary in cases when the method should return Page.

Obviously that while using the requests we should point the parameters for the requests. There’s the @Param annotation:

@Query("select u from User u where u.login = :login and u.password = :password")
Page<User> findByLoginAndPassword(@Param("login") String login, @Param("password") String password);

In addition, Spring Data JPA supports the concept of different specifications. The specifications allow you to make up complex queries from the set of simple ones. To support the specifications it is necessary to declare a method in the repository.

Page<User> findAll(Specification<User> spec, Pageable pageable);

The specification is essentially a filter and allows the combination of filters which makes it a powerful tool for building queries. An example of the use of specifications: Let’s declare our specifications:

public static Specification<User> firstNameOrLastNameOrLoginLike(final String search) {
    return new Specification<User>() {
        @Override
        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
 
            Predicate loginPredicate = builder.like(root.get(User_.login), search);
            Predicate firstnamePredicate = builder.like(root.get(User_.firstname), search);
            Predicate lastnamePredicate = builder.like(root.get(User_.lastname), search);
 
            return builder.or(loginPredicate, firstnamePredicate, lastnamePredicate);
        }
    };
}
 
public static Specification<User> hasRole(final Role role) {
    return new Specification<User>() {
        @Override
        public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            return builder.equal(root.get(User_.role), role);
        }
    };
}

And combine them in our service:

public Page<User> searchUser(Role role, String search, Pageable pageable) {
    Specifications<User> mainSpec = where(hasRole(role));
 
    // уточняем запрос, если была передана строка для поиска
    if (StringUtils.isNotBlank(search)) {
        mainSpec = mainSpec.and(firstNameOrLastNameOrLoginLike(search));
    }
 
    return userRepository.findAll(mainSpec, pageable);
}
11
Jul

Own implementation of methods in Spring Data JPA

Posted by eugene as Spring Data

Obviously we cannot always use the automatic code generation provided by Spring Data JPA. For example, we have a very complicated request or we need to call a procedure in database or we have complex business logic. Consider the following example – for example we need functionality of the counter which we decided to implement with the help of sequence. First of all we define an interface where we describe all the methods that we’ll implement by ourselves. In our case this will be only one method.

public interface UserRepositoryCustom {
    /**
     * Returns next unique id.
     *
     * @return next unique id.
     */
    Integer getNextUniqueId();
}

Next we’ll update the repository announcement so that it will inherit a new UserRepositoryCustom interface

public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
   ...
}

Now let’s write up the method realization:

public class UserRepositoryImpl implements UserRepositoryCustom {
 
    @PersistenceContext
    private EntityManager entityManager;
 
    @Override
    public Integer getNextUniqueId() {
 
        // When using Hibernate via JPA native queries fails with mapping exception, so just use Hibernate directly:
        Session session = (Session) entityManager.getDelegate();
        SQLQuery nativeQuery = session.createSQLQuery("SELECT \"nextval\"('unique_id_seq') ");
        List<BigInteger> list = nativeQuery.list();
        if (list.isEmpty()) {
            throw new IncorrectResultSizeDataAccessException(1);
        }
 
        BigInteger result = list.get(0);
 
        return result.intValue();
    }
}

And finally let’s point out Spring Data JPA so that our class with the implementation of its own methods will be used as a proxy class. To do this we need another section of the repositories in the configuration file:

<repositories base-package="[base.repository.package]"/>
 
<repositories base-package="[base.repository.package]">
    <repository id="userRepository" custom-impl-ref="userRepositoryImpl"/>
</repositories>
 
<beans:bean id="userRepositoryImpl" class="...UserRepositoryImpl"/>

And that is all.

11
Jul

Implementation of concurrent HashSet in Java

Posted by eugene as Java

Undortunately there’s no full implementation of a concurrent HashSet as in case with HashMap – java.util.concurrent.ConcurrentHashMap. There’s CopyOnWriteArraySet which uses CopyOnWriteArrayList inside of it but it has some disadvantages:

  • Searching of elements will be slower as it’s implemented by equals in Lists and not by hashcode -> equals.
  • Inability to remove objects while iterating (iterator.remove () – not implemented) and it is clear why not as the collection copy is used while the iteration.

But out there ConcurrentHashSet can be done on the basis of ConcurrentHashMap writing down an element as the key and any dummy-object into the value. Such implementation is represented in the form of org.jboss.util.collection.ConcurrentSet from the jboss-common-core library.

10
Jul

Using of Javassist for generating proxy in Spring Framework

Posted by eugene as Spring Framework

It is well known that the cglib project has had been long in the abandoned state, also when working with it there appear some problems described below. The most popular alternative for this project is javassist. It is used in such projects as JBoss AS, Hibernate, Weld…

But it hasn’t yet appeared in Spring only. The replacement of the cglib library used to generate the proxy objects with the javassist will be implemented in version 3.1 according to the project plan. In the same task I’ve attached three classes and couples of patches which allow to finally change your approach to Javassist.

To enable Javassist you need to attach these three classes to my project – JavassistAopProxy, JavassistAopProxyFactory and JavassistApplicationContext. Then, instead of the spring realization of ApplicationContext use org.springframework.aop.framework.JavassistApplicationContext. If you are not creating it directly and use org.springframework.web.context.ContextLoaderListener configured in web.xml then you will need to add the following lines into the same web.xml:

<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.aop.framework.JavassistApplicationContext</param-value>
</context-param>