Hibernate keep coonection after explisit destroying service registry

My goal is to generate DDL during build time. I have exec-maven-plugin with goal to execute main method below:

public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
        SessionFactoryImpl sessionFactory = null;
        try {
            Persistence.generateSchema(PERSISTENCE_UNIT, null);
        } finally {
            sessionFactory = emf.unwrap(SessionFactoryImpl.class);
            sessionFactory.getServiceRegistry().destroy();
        }
}

my persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="ddl-gen">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <class>***</class>
        <class>***</class>
        <class>***</class>

        <properties>


            <property name="javax.persistence.schema-generation.scripts.action" value="create"/>
            <property name="javax.persistence.schema-generation.scripts.create-target"
                      value="${project.basedir}/src/main/resources/META-INF/sql/init.sql"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://***/~/***"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>



        </properties>

    </persistence-unit>

</persistence>

But the problem is Hibernate wont kill DB connection even if I do it explicitly. Execution does not finishing and the process is endless

Logs:

16:11:41.062 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry - Not binding SessionFactory to JNDI, no JNDI name configured
16:11:41.062 [main] DEBUG org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator - wasInitiallyAutoCommit=false
16:11:41.062 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
16:11:41.066 [main] DEBUG org.hibernate.service.internal.AbstractServiceRegistryImpl - Implicitly destroying ServiceRegistry on de-registration of all child ServiceRegistries
16:11:41.066 [main] INFO org.hibernate.orm.connections - HHH10001008: Cleaning up connection pool [jdbc:h2:tcp://***/~/***]
16:11:41.067 [main] DEBUG org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl - Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries
16:12:10.932 [pool-2-thread-1] DEBUG org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl - Connection pool now considered primed; min-size will be maintained

Intresting thing is that I have [pool-2-thread-1] It means Hibernate creates new pool. because without explisit killing i have this log:

public static void main(String[] args) {
    Persistence.generateSchema(PERSISTENCE_UNIT, null);
}

16:07:26.890 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry - Not binding SessionFactory to JNDI, no JNDI name configured
16:07:26.895 [main] DEBUG org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator - wasInitiallyAutoCommit=false
16:07:26.896 [main] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
16:07:54.274 [pool-1-thread-1] DEBUG org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl - Connection pool now considered primed; min-size will be maintained

JavaFX: Adding a Label as child to a TextField

I want to have a text displayed above a JavaFX-TextField. Setting the prompText is almost what I want, but has some drawbacks for my use case. The following code seems to work, but it feels wrong to add a Label to the children of the TextField. Does the following code violate any JavaFX principles or is it safe to use?

public class MyTextField extends TextField {    
    public MyTextField() {
        Label label = new Label("test");
        this.getChildren().add(label);
    }  
}

How can I measure how many threads are executing a piece of code?

I am trying to measure how many threads are executing a section of code at the same time.
Currently i am (ab)using Semaphores for this, is there a better way?

final int MAX_THREADS = Integer.MAX_VALUE;

Semaphore s = new Semaphore(MAX_THREADS);

s.acquire(); // start of section

// do some computations

// track how many threads are running the section
trackThreads( (MAX_THREADS - s.availablePermits()) );         

s.release(); // end of section

Command Pattern in Java SE Swing Application

at the moment i am trying to develop a basic Java SE Swing based Application.
The Applications aim is to provide a simple CRUD functionality for saving data within a list.

I want to code this as clean as possible and introduced the MVC pattern. For the ADD/Delete/… operations i want to use the Command pattern in order to can also provide undo and redo then later.

With this an understanding problem popped up.
The new data items can be added or edited for example by an dialog. As im using MVC, the controller register itself for example to the new button and triggers a an “open dialog method” within the view.

My question is, how i add this functionality now to the single command which can instead open the dialog within the view. During deletion for example, i have to close the dialog AND call the save operation within the service. Should this both handled within one “saveAndCloseCommand” for example?

Another issue here is, if i save all executed commands into a command list within controller or separate invoker for example, how can i to the redo correctly? I mean a command “OpenDialogCommand” is not needed to be undod. Should i introduce here different Command types for controls and actual service modification commands?

It would be nice if anybody could give me some advice how to to this correctly.

Thanks!

Maven : jar file not generated

I have a basic SpringBoot app generated with Spring Tool Suite, Version: 3.9.1.RELEASE, with this pom.xml file, but when I run mvn clean package the jar file is not generated inside the target folder, even the other folders are generated and the application runs OK when I run it inside Eclipse

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.telefonica.handler</groupId>
    <artifactId>telefonicaTeltonikaHandler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>telefonicaTeltonikaHandler</name>
    <description>telefonica Teltonika Handler</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
          <!-- Logging dependencies -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>    
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Testing IllegalArgumentException is not catching as expected

I have the following testing code:

@Test(expected = IllegalArgumentException.class)
public void addPlayerFailureTest()    {
    playerDAO.addPlayer(null);
}

This code is supposed to return an IllegalArgumentException, and it does as expected. However, it turns the test red. This is the stacktrace:

ERROR  addPlayer, Player failure: 
java.lang.IllegalArgumentException: attempt to create merge event with null entity
    at org.hibernate.event.MergeEvent.<init>(MergeEvent.java:60)
    at org.hibernate.event.MergeEvent.<init>(MergeEvent.java:43)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:688)
    at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:692)
    at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:235)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
    at com.sun.proxy.$Proxy32.merge(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    at com.sun.proxy.$Proxy32.merge(Unknown Source)
    at fr.game.core.dao.AbstractJpaGenericDAO.update(AbstractJpaGenericDAO.java:58)
    at fr.game.core.dao.player.JPAJoueurDAO.addJoueur(JPAJoueurDAO.java:40)
    at fr.game.core.dao.player.JoueurDAOTest.addJoueurFailureTest(JoueurDAOTest.java:23)

I am supposed to receive this exception, yet I cannot. I met the same behavior when testing a wrong value in an Enum.

Why does it make my test fail ? Is it because the exception is thrown from such a place that it cannot be caught that way ?

Reddit Api unsupported_grant_type error with Retrofit (java)

I am using the “Token Retrieval (code flow)” as outlined here to retrieve an access token via OAuth2 for the Reddit Api. I have managed to get the “code” String, but I get an unsupported_grant_type error when attempting to retrieve the access token. I would like to use Retrofit2 to accomplish this.

private void getAccessToken(String code) {

    if (mRetrofit == null) {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(RedditConstants.REDDIT_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    Api api = mRetrofit.create(Api.class);

    String authString = RedditConstants.REDDIT_CLIENT_ID + ":";
    String encodedAuthString = Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    Map<String, String> headers = new HashMap<>();
    // headers.put("Content-Type", "application/x-www-form-urlencoded");
    // headers.put("Accept", "application/json");
    headers.put("Authorization", "Basic " + encodedAuthString);
    headers.put("grant_type" , "authorization_code");
    headers.put("code", code);
    headers.put("redirect_uri", RedditConstants.REDDIT_REDIRECT_URL);
    headers.put("User-Agent", RedditConstants.REDDIT_USER_AGENT);

    Call<RedditAccessToken> call = api.login(headers, MediaType.parse("application/x-www-form-urlencoded"));
    call.enqueue(new Callback<RedditAccessToken>() {
        @Override
        public void onResponse(Call<RedditAccessToken> call, Response<RedditAccessToken> response) {
                Log.d("Findme", "body: " + response.body().toString());
                Log.d("Findme", "response: " + response.toString());
        }

        @Override
        public void onFailure(Call<RedditAccessToken> call, Throwable t) {
            Log.e("Fineme", "onFailure: " + t.getMessage());
        }
    });

}

Log Results:

D/Findme: body: RedditAccessToken{scope='null', token_type='null', 
error='unsupported_grant_type', expires_in='0', access_token='null', 
refresh_token='null'}
D/Findme: response: Response{protocol=h2, code=200, message=, 
url=https://www.reddit.com/api/v1/access_token/}

Retrofit Interface:

public interface Api {

    @POST("access_token/")
    Call<RedditAccessToken> login (
        @HeaderMap Map<String, String> headers,
        @Header("Content-Type") MediaType contentType
    );
}

Retrofit Data Model:

public class RedditAccessToken {

    @SerializedName("scope")
    @Expose
    private String scope;

    @SerializedName("token_type")
    @Expose
    private String token_type;

    @SerializedName("expires_in")
    @Expose
    private long expires_in;

    @SerializedName("access_token")
    @Expose
    private String access_token;

    @SerializedName("refresh_token")
    @Expose
    private String refresh_token;

    @SerializedName("error")
    @Expose
    private String error;

    public String getScope() {
        return scope;
    }

    public String getRefresh_token() {
        return refresh_token;
    }

    public void setRefresh_token(String refresh_token) {
        this.refresh_token = refresh_token;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public String getToken_type() {
        return token_type;
    }

    public void setToken_type(String token_type) {
        this.token_type = token_type;
    }

    public long getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(long expires_in) {
        this.expires_in = expires_in;
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    @Override
    public String toString() {
        return "RedditAccessToken{" +
                "scope='" + scope + ''' +
                ", token_type='" + token_type + ''' +
                ", error='" + error + ''' +
                ", expires_in='" + expires_in + ''' +
                ", access_token='" + access_token + ''' +
                ", refresh_token='" + refresh_token + ''' +
                '}';
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}

RxJava 2 – Reduce queue in concatMap

I have a subject that emits some data. Then I want to modify this data in the queue (long operation). But when another subject will emit other things I want to reduce my queue

    PublishSubject<Integer> myBaseSubject = PublishSubject.create();
    PublishSubject<Integer> otherSubject = PublishSubject.create();

    myBaseSubject
            .concatMap(integer -> Observable.timer(5, TimeUnit.SECONDS) // long operation
                    .map(aLong -> integer)
            )
            .subscribe(
                    integer -> Log.i(TAG, "result: " + integer),
                    Functions.emptyConsumer()
            );

    myBaseSubject.onNext(1);
    myBaseSubject.onNext(2);
    myBaseSubject.onNext(3);
    myBaseSubject.onNext(4); 
    myBaseSubject.onNext(5);

    otherSubject.onNext(3);
    otherSubject.onNext(4);

    myBaseSubject.onNext(6);
    myBaseSubject.onNext(7);

Now I want to modify my disposable to skip elements emited by otherSubject (3 and 4) if those elements aren’t already consumed by concatMap(they are still in queue).

Is it possible to achieve that?

PS: PublishSubject is not required – it’s used just for simplicity