azizkhani.net

I know that I know nothing

datasource Initializer for run sql script

clock July 21, 2016 23:40 by author Administrator

some time our application have initial data or sometimes needs to run sql script to create tables or other database object when application init.

 

in this code when can do that very simple and easy by spring boot 

 

@Inject

private DataSource dataSource;

 

@Value("classpath:schema.sql")

 private Resource schemaScript;


@Bean

public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {

         final DataSourceInitializer initializer = new DataSourceInitializer();

        initializer.setDataSource(dataSource);

        initializer.setDatabasePopulator(databasePopulator());

        returninitializer;

}

private DatabasePopulator databasePopulator() {

        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();

        populator.addScript(schemaScript);

        returnpopulator;

 



how to set redis key time out (spring session timeout) maxInactiveInterval

clock October 6, 2015 20:22 by author Administrator

 

when using spring session in a container when http session is time out session or key that store in redis dose not time out for solve this problem and set timeout or that config like this code 


<beanclass="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"p:maxInactiveIntervalInSeconds="180"/>



how to change default redis ip in spring boot

clock September 4, 2015 16:26 by author Administrator

i run redis in docker .my docker ip is 192.168.99.100 and redis port 32768

but my spring session default host & port is 127.0.0.1 and 6379 

for change redis port in docker i run container by " docker-compose up " command

using this file docker-compose.yml


redis:

  image: redis

  ports:

     - "6379:6379"

after run docker i can monitor to redis by this command
telnet 192.168.99.100 6379
and redis is ok


but after run spring session and redis i can not connect to them 
after search i know that how change default host in spring boot application.yml

spring:

  redis:

    host: 192.168.99.100



send email after commit using spring transaction

clock May 6, 2015 21:22 by author Administrator

Sometimes you want a little more control over transaction but at the same time you don't want to switch to programmatic transaction management. I'm talking about cases when you want to execute some activities only when transaction was completed successfully. For example: send an email with registration details, update a cache, send a message over network, etc. The tricky part here is that you want to perform these activities from a transactional method (a method marked with @Transactional which automatically will start and end the transaction).

 

@Component
public class AfterCommitExecutorImpl extends TransactionSynchronizationAdapter implements AfterCommitExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutorImpl.class);
    private static final ThreadLocal<List<Runnable>> RUNNABLES = new ThreadLocal<List<Runnable>>();

    @Override
    public void execute(Runnable runnable) {
        LOGGER.info("Submitting new runnable {} to run after commit", runnable);
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            LOGGER.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {}", runnable);
            runnable.run();
            return;
        }
        List<Runnable> threadRunnables = RUNNABLES.get();
        if (threadRunnables == null) {
            threadRunnables = new ArrayList<Runnable>();
            RUNNABLES.set(threadRunnables);
            TransactionSynchronizationManager.registerSynchronization(this);
        }
        threadRunnables.add(runnable);
    }

    @Override
    public void afterCommit() {
        List<Runnable> threadRunnables = RUNNABLES.get();
        LOGGER.info("Transaction successfully committed, executing {} runnables", threadRunnables.size());
        for (int i = 0; i < threadRunnables.size(); i++) {
            Runnable runnable = threadRunnables.get(i);
            LOGGER.info("Executing runnable {}", runnable);
            try {
                runnable.run();
            } catch (RuntimeException e) {
                LOGGER.error("Failed to execute runnable " + runnable, e);
            }
        }
    }

    @Override
    public void afterCompletion(int status) {
        LOGGER.info("Transaction completed with status {}", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK");
        RUNNABLES.remove();
    }

}

 

example:

final String email = user.getEmail();
            afterCommitExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    mailService.sendMail(email, "CreateUser", params, "templates/email/CreateUser.ftl");
                }
            });



How does @RequestParam in Spring handle Optional?

clock December 31, 2014 20:04 by author Administrator
@RequestMapping("foo")
@ResponseBody
public String foo(@RequestParam(required =false) final Optional name){
return"name: "+(name ==null?"null": name.get());
}


@Autowired and static method

clock December 23, 2014 16:09 by author Administrator

@Component
public class Boo {

    private static Foo foo;

    @Autowired
    public Boo(Foo foo) {
        Boo.foo = foo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}


@Component
public class Boo {

    private static Foo foo;
    @Autowired
    private Foo tFoo;

    @PostConstruct
    public void init() {
        Boo.foo = tFoo;
    }

    public static void randomMethod() {
         foo.doStuff();
    }
}



@Platform and @Qualifier

clock November 11, 2014 22:23 by author Administrator

@Autowired
private MarketPlace marketPlaces;


@Autowired
@Qualifier( "ios") // the use is unique to Spring. It's darned convenient, too!
 private MarketPlace marketPlaces;



and now jsr 330




package spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static spring.Spring.Platform;

@Configuration
@ComponentScan
public class Spring {

    public static void main(String[] args) {
        new AnnotationConfigApplicationContext(Spring.class);
    }

    @Autowired
 @Platform(Platform.OperatingSystems.ANDROID)
    private MarketPlace android;

    @Autowired
 @Platform(Platform.OperatingSystems.IOS)
    private MarketPlace ios;

    @PostConstruct
    public void qualifyTheTweets() {
        System.out.println("ios:" + this.ios);
        System.out.println("android:" + this.android);
    }

    // the type has to be public!
    @Target({ElementType.FIELD,
            ElementType.METHOD,
            ElementType.TYPE,
            ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Qualifier
    public static @interface Platform {

        OperatingSystems value();

        public static enum OperatingSystems {
            IOS,
            ANDROID
        }
    }
}

interface MarketPlace {
}

@Component
@Platform(Platform.OperatingSystems.IOS)
class AppleMarketPlace implements MarketPlace {

    @Override
    public String toString() {
        return "apple";
    }
}

@Component
@Platform(Platform.OperatingSystems.ANDROID)
class GoogleMarketPlace implements MarketPlace {

    @Override
    public String toString() {
        return "android";
    }
}


@RequestHeader in Spring MVC

clock June 21, 2014 20:01 by author Administrator

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RequestHeaderExampleController{
    @RequestMapping(value = "/example", method = RequestMethod.GET)
    public String  getHello(@RequestHeader ("host") String hostName,
            @RequestHeader ("Accept") String acceptType,
            @RequestHeader ("Accept-Language") String acceptLang,
            @RequestHeader ("Accept-Encoding") String acceptEnc,
            @RequestHeader ("Cache-Control") String cacheCon,
            @RequestHeader ("Cookie") String cookie,
            @RequestHeader ("User-Agent") String userAgent){
        System.out.println("Host : " + hostName);
        System.out.println("Accept : " + acceptType);
        System.out.println("Accept Language : " + acceptLang);
        System.out.println("Accept Encoding : " + acceptEnc);
        System.out.println("Cache-Control : " + cacheCon);
        System.out.println("Cookie : " + cookie);
        System.out.println("User-Agent : " + userAgent);
        return "example";
    }
}




retrieve currently logged-in users using the SessionRegistry

clock December 28, 2012 17:04 by author Administrator

http://krams915.blogspot.de/2010/12/spring-security-mvc-querying.html

 

http://code.google.com/p/spring3-security-mvc-integration-tutorial/downloads/detail?name=spring-mvc.zip&can=2&q=



ROW LEVEL SECURITY (BEST SOLUTION?)

clock October 25, 2012 19:21 by author Administrator

 

HELP ME
here might be special rows in a database which should only visible and accessible by users with special privileges. To avoid unnecessary round-trips, we currently modify the SQL queries to join with our authorization data to get only the visible rows for the current user.

But this concepts doesn't feel 'right' to me, because we mix business code with security related code which should be orthogonal and independent from each other.

 

  • What solutions are available/possible?
  • How do you implement row-level security (especially in combination with hibernate)?

The idea is that you can implement row level functionality in two ways: directly setting restrictions in your repository or binding the restrictions via AOP. The latter is preferred because security layer should be separated from business logic (orthogonal concerns).

 

In Hibernate you can use the concept of filters which are applied transparently and repository doesn't know about them. You can add such filters via AOP. The other way is intercepting session.createCriteria() and adding Restrictions to the Criteria transparently using AOP.

 



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In