dimanche 26 juin 2016

Spring Tests failing on Spring Tool Suite

When I run my unit tests with maven, everything goes well, but when I try to run it inside Spring Tool Suite the console ouputs a message about SLF4j and the test fails

The console output:

SLF4J: This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.

The Test failing trace:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [database-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchFieldError: TRACE
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.eminer.dao.ApplicationContextXMLConfigTest.should_load_context_from_xml(ApplicationContextXMLConfigTest.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:670)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.NoSuchFieldError: TRACE
    at org.jboss.logging.Log4jLogger.translate(Log4jLogger.java:64)
    at org.jboss.logging.Log4jLogger.doLog(Log4jLogger.java:44)
    at org.jboss.logging.Logger.trace(Logger.java:128)
    at org.hibernate.internal.CoreMessageLogger_$logger.trace(CoreMessageLogger_$logger.java:417)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1311)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
    at org.springframework.orm.jpa.vendor.SpringHibernateEjbPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateEjbPersistenceProvider.java:51)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    ... 35 more

My pom.xml

<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.eminer</groupId>
    <artifactId>eminer-dao</artifactId>
    <name>eminer-dao</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>

    <properties>
        <org.springframework-version>4.1.6.RELEASE</org.springframework-version>
        <hamcrest.version>1.3</hamcrest.version>
        <org.slf4j.version>1.7.5</org.slf4j.version>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.restfb</groupId>
            <artifactId>restfb</artifactId>
            <version>1.9.0</version>
        </dependency>

        <dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.5.1</version>
        </dependency>

        <!-- eMiner -->

        <dependency>
            <groupId>com.eminer</groupId>
            <artifactId>eminer-model</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Spring Data and Transaction -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-core</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-amqp</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.1.9.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <!-- Teste -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>${hamcrest.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>${hamcrest.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>

        <!-- Log -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>


        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Context-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <!-- Integration and Rabbit Configuration -->
    <import resource="classpath:integration-context.xml" />

    <!-- Spring Container -->
    <jpa:repositories base-package="com.eminer.*" />
    <context:component-scan base-package="com.eminer.*" />
    <tx:annotation-driven/>

    <!-- DataBase -->

    <import resource="classpath:database-context.xml" />

</beans>

integration-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
    xsi:schemaLocation="http://www.springframework.org/schema/integration/amqp http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.1.xsd">

    <import resource="classpath:rabbit-context.xml" />

    <!-- ERROR LOGIN CONFIG -->

    <int:channel id="errorChannel"/>

    <int:logging-channel-adapter  
        id="logger" 
        level="ERROR" 
        channel="errorChannel" />

    <!-- PAGE PERSISTER -->
    <int-amqp:inbound-channel-adapter 
        id="pagePersisteQueueSubscriber" 
        channel="pagesToPersiste" 
        connection-factory="connectionFactory"  
        queue-names="eminer.page.persist" 
        auto-startup="true"  />

    <int:channel id="pagesToPersiste"/>

    <int:service-activator 
        method="subscribe" 
        ref="facebookPageSubscriber" 
        input-channel="pagesToPersiste"/>


    <!-- POST PERSISTER -->
    <int-amqp:inbound-channel-adapter 
        id="RabbitOut" 
        channel="postsToPersist" 
        connection-factory="connectionFactory" 
        queue-names="eminer.post.persist" 
        auto-startup="true" />

    <int:channel id="postsToPersist"/>

    <int:service-activator  
        ref="postSubscriber"
        method="subscribe" 
        input-channel="postsToPersist"
        output-channel="toHeaderEnricher"/>

    <int:channel id="toHeaderEnricher"  datatype="java.lang.String" />

    <int:header-enricher 
        input-channel="toHeaderEnricher"  
        output-channel="toRabbitPostsIds">
        <int:header 
            name="content_type" 
            value="text/plain">
        </int:header>
    </int:header-enricher>

    <int:channel 
        id="toRabbitPostsIds"  
        datatype="java.lang.String" />

    <int-amqp:outbound-channel-adapter  
        amqp-template="amqpTemplate" 
        channel="toRabbitPostsIds" 
        exchange-name="eminer.exchange" 
        id="postIdsPublisherChannelAdapter" 
        routing-key="eminer.post.id.binding" 
        header-mapper="postIdMapper"/>

    <bean 
        id="postIdMapper" 
        class="org.springframework.integration.amqp.support.DefaultAmqpHeaderMapper">
        <property 
            name="requestHeaderNames" value="content_type"/>
    </bean>

    <!-- COMMENT PERSISTERS -->

    <int-amqp:inbound-channel-adapter 
        id="commentsRabbitOut"   
        channel="toJasonToObjectTransformer" 
        connection-factory="connectionFactory" 
        queue-names="eminer.comment.persist" 
        auto-startup="true" 
        error-channel="errorChannel"/>

    <int:channel id="toJasonToObjectTransformer" />

    <int:json-to-object-transformer input-channel="toJasonToObjectTransformer" output-channel="commentsFromRabbit" />

    <int:channel id="commentsFromRabbit"/>

    <int:service-activator 
        id="commentPersister" 
        method="subscribe"
        input-channel="commentsFromRabbit" 
        ref="facebookCommentPersisterSubscriber" 
          />

    <!-- REPORT QUERY -->
    <int-amqp:inbound-channel-adapter 
        id="RabbitReportQueryOut"
        channel="reportQueries" 
        connection-factory="connectionFactory" 
        queue-names="eminer.reports.queries" auto-startup="false" />

    <int:channel id="reportQueries"/>
    <int:service-activator  method="subscribe" ref="reportQuerySubscriber"
         input-channel="reportQueries"
         output-channel="toReportResults"/>
    <int:channel id="toReportResults"/>

    <int-amqp:outbound-channel-adapter 
        amqp-template="amqpTemplate" 
        channel="toReportResults" 
        exchange-name="eminer.exchange" 
        id="queryResultPublisherChannelAdapter" 
        routing-key="eminer.reports.queriesresults.binding"/>

</beans>

rabbit-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.4.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <rabbit:connection-factory id="connectionFactory" host="localhost" port="5672"/>
    <rabbit:template connection-factory="connectionFactory" id="amqpTemplate"  />

    <rabbit:admin connection-factory="connectionFactory" auto-startup="false"/>

    <rabbit:queue name="eminer.comment.persist"/>
    <rabbit:queue name="eminer.post.persist"/>
    <rabbit:queue name="eminer.post.id"/>
    <rabbit:queue name="eminer.reports.queries"/>
    <rabbit:queue name="eminer.reports.queriesresults"/>
    <rabbit:queue name="eminer.page.persist"/>

    <rabbit:direct-exchange name="eminer.exchange">
        <rabbit:bindings>
            <rabbit:binding key="eminer.reports.queriesresults.binding" queue="eminer.reports.queriesresults"/>
            <rabbit:binding key="eminer.page.persist.binding"       queue="eminer.page.persist"/>
            <rabbit:binding key="eminer.post.persist.binding"       queue="eminer.post.persist"/>
            <rabbit:binding key="eminer.post.id.binding"            queue="eminer.post.id"/>
        </rabbit:bindings>
    </rabbit:direct-exchange>

</beans>

database-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd">

    <jpa:repositories base-package="com.eminer.*" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/eminer" />
        <property name="username" value="user" />
        <property name="password" value="pass" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.eminer.*" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false" />
                <property name="generateDdl" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
            </bean>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
</beans>

maven dependency tree

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building eminer-dao 1.0.0-BUILD-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ eminer-dao ---
[INFO] com.eminer:eminer-dao:war:1.0.0-BUILD-SNAPSHOT
[INFO] +- com.restfb:restfb:jar:1.9.0:compile
[INFO] +- net.sf.dozer:dozer:jar:5.5.1:compile
[INFO] |  +- commons-beanutils:commons-beanutils:jar:1.9.1:compile
[INFO] |  |  - commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  +- org.apache.commons:commons-lang3:jar:3.2.1:compile
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.5:compile
[INFO] |  - org.slf4j:jcl-over-slf4j:jar:1.7.5:compile
[INFO] +- com.eminer:eminer-model:jar:0.0.1-SNAPSHOT:compile
[INFO] +- org.springframework:spring-context:jar:4.1.6.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.1.6.RELEASE:compile
[INFO] |  |  - aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.1.6.RELEASE:compile
[INFO] |  +- org.springframework:spring-core:jar:4.1.6.RELEASE:compile
[INFO] |  - org.springframework:spring-expression:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework:spring-webmvc:jar:4.1.6.RELEASE:compile
[INFO] |  - org.springframework:spring-web:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.3.0.RELEASE:compile
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.5.0.RELEASE:compile
[INFO] |  - org.aspectj:aspectjrt:jar:1.7.1:compile
[INFO] +- org.springframework:spring-orm:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework:spring-jdbc:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework:spring-tx:jar:4.1.6.RELEASE:compile
[INFO] +- org.springframework.integration:spring-integration-core:jar:4.1.6.RELEASE:compile
[INFO] |  +- org.projectreactor:reactor-core:jar:1.1.4.RELEASE:compile
[INFO] |  |  +- com.goldmansachs:gs-collections:jar:5.1.0:compile
[INFO] |  |  |  - com.goldmansachs:gs-collections-api:jar:5.1.0:compile
[INFO] |  |  +- com.lmax:disruptor:jar:3.2.1:compile
[INFO] |  |  - io.gatling:jsr166e:jar:1.0:compile
[INFO] |  +- org.springframework:spring-messaging:jar:4.1.6.RELEASE:compile
[INFO] |  - org.springframework.retry:spring-retry:jar:1.1.1.RELEASE:compile
[INFO] +- org.springframework.integration:spring-integration-amqp:jar:4.1.6.RELEASE:compile
[INFO] |  - org.springframework.amqp:spring-rabbit:jar:1.4.5.RELEASE:compile
[INFO] |     +- com.rabbitmq:amqp-client:jar:3.5.1:compile
[INFO] |     - org.springframework.amqp:spring-amqp:jar:1.4.5.RELEASE:compile
[INFO] +- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:jar:1.0.1.Final:compile
[INFO] +- org.hibernate:hibernate-entitymanager:jar:4.1.9.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.0.GA:compile
[INFO] |  +- org.javassist:javassist:jar:3.17.1-GA:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.1_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:4.1.9.Final:compile
[INFO] |  |  - antlr:antlr:jar:2.7.7:compile
[INFO] |  - org.hibernate.common:hibernate-commons-annotations:jar:4.0.1.Final:compile
[INFO] +- mysql:mysql-connector-java:jar:5.1.35:compile
[INFO] +- junit:junit-dep:jar:4.10:test
[INFO] +- org.springframework:spring-test:jar:4.1.6.RELEASE:test
[INFO] +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.mockito:mockito-core:jar:1.10.19:test
[INFO] |  - org.objenesis:objenesis:jar:2.1:test
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.7.5:compile
[INFO] +- log4j:log4j:jar:1.2.17:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.5.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.5.0:compile
[INFO] |  - com.fasterxml.jackson.core:jackson-core:jar:2.5.3:compile
[INFO] - javax.servlet:javax.servlet-api:jar:3.1.0:provided
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.077 s
[INFO] Finished at: 2016-06-25T19:51:03-03:00
[INFO] Final Memory: 14M/179M
[INFO] ------------------------------------------------------------------------

I have no idea why this is happening.

Starting content container over bottom section of image

So I want to show my content showing over my image, but only slightly. So in a sense the image would look like it was partly the background of the page. I do not want my content box to stretch over the full width of the page like the image currently does however.

This is the page I am working on; http://outside.hobhob.uk/test/?portfolio=mind-the-gap-2

This is what I am aiming to have it look similar to (focusing just on how the content text box is slightly over the image): https://s32.postimg.org/ytavty67p/13340631_10154339496581336_223276410_o.jpg

Is there a way I can achieve this with maybe changing the css of the content box slightly? Maybe changing the position or z-index?

The code of the page is currently working in a typical way, I am also using Visual Composer to lay out the content in the page, so this may help me achieve this in a easier way?

<div class="pagewidth">
  <div class="content single single-portfolio">
    <div class="post-content">
      <article id="post-<?php the_ID(); ?>" <?php post_class("post post-content-full"); ?>>
        <div class="portfolio-attachment">
          <?php
            $pi_data = get_port_item_content(get_the_ID());
            $n = 0;
            the_post_thumbnail();
            if ($pi_data) {
              foreach ($pi_data as $content_info) {
                switch ($content_info->type) {
                  case "image":
                    ?>
                      <div class="item image"><img
                        src="<?php echo $content_info->url?>"/></div>
                      <?php
                    break;
                  case "youtube":
                    //check to see if the video has any options, the ? sign
                    $has = strstr($content_info->url, "?");

                    if (!$has) {
                      $embed = explode('"', $content_info->url);
                      // insert enablejsapi option
                      $embed[5] .= "?wmode=transparent";
                      $embed = implode('"', $embed);
                    } else {
                      // insert enablejsapi option
                      $embed = str_ireplace("&", "&amp;", $content_info->url);
                      $embed = str_ireplace("?", "?wmode=transparent&amp;", $embed);
                    }

                    // get original dimensions
                    $pattern = "/height="[0-9]*"/";
                    preg_match($pattern, $embed, $matches);
                    $origHeight = preg_replace("/[^0-9]/", '', $matches[0]);

                    // compute new height
                    //$newHeight = $origHeight + 25;
                    $newHeight = $origHeight;

                    // adjust embed code
                    $pattern = "/height="[0-9]*"/";
                    $embed = preg_replace($pattern, "height='" . $newHeight . "'", $embed);

                    // insert an id for the iframe
                    $id = '<iframe id="ytplayer' . $n . '" ';
                    $embed = str_ireplace("<iframe ", $id, $embed);
                    ?>
                      <div class="item youtube fitvid"><?php echo $embed?></div>
                      <?php
                    break;
                  case "vimeo":
                    $embed = $content_info->url;
                    ?>
                      <div class="item vimeo fitvid"><?php echo $embed?></div>
                      <?php
                    break;
                }
                //end switch
                $n++;
              } //end for each
            }//end if
          ?>
      </div>
</div></div></div>
<div class="pagewidth-single">
<div class="content single single-portfolio">
  <div class="post-content">
    <header class="content-headarea">
      <div class="content-headarea-title">
&nbsp;
&nbsp;
        <h1 class="post-title"><?php the_title(); ?></h1>
        <ul class="portfolio-meta">
          <?php $client = get_post_meta(get_the_ID(), 'client', true); ?>
          <?php if (!empty($client)) : ?>
          <li class="client">
            <span class="portfolio-meta-heading"><?php _e('Client: ', 'framework'); ?></span>
            <span><?php echo $client ?></span>
          </li>
          <?php endif; ?>
          <?php $date = get_post_meta(get_the_ID(), 'date', true); ?>
          <?php if (!empty($date)) : ?>
          <li class="date">
            <span class="portfolio-meta-heading"><?php _e('Date: ', 'framework'); ?></span>
            <span><?php echo $date ?> </span>
          </li>
          <?php endif; ?>
          <?php $lproj = get_post_meta(get_the_ID(), 'url', true);
          if (!empty($lproj)) :
          ?>
          <li class="launch">
            <span class="portfolio-meta-heading"><?php _e('url', 'framework'); ?></span>
            <a href="<?php echo get_post_meta(get_the_ID(), 'url', true); ?>"
              class="superlink"
              title="<?php echo get_post_meta(get_the_ID(), 'url', true); ?>">
              <?php echo get_post_meta(get_the_ID(), 'url', true); ?>
            </a>
          </li>
          <?php endif; ?>
        </ul>
      </div>
    </header>      
        <div class="blog-post">
          <div class="full-post">
            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
              <?php the_content(); ?>
            <?php endwhile; ?>
            <?php else:?>

            <?php endif; ?>
          </div>
        </div>

        <?php get_template_part( '/includes/share'); ?>
        <?php comments_template(); ?>

        <nav id="post-nav">
          <div class="post-nav-inner">
            <div class="nav-previous"><?php next_post_link( '%link', __( 'Next Post &rarr;', 'framework' ) ); ?></div>
            <div class="nav-next"><?php previous_post_link( '%link', __( '&larr; Previous Post', 'framework' ) ); ?></div>
            <div class="clearfix"></div>
          </div>
        </nav>

      </article>
    </div>
  </div>
</div>

So I am looking to start the overlay on the <header> section, from the page title onwards, while keeping the featured image as the full width background'ish half section. I want to avoid having the image basically cover the screen and so you can begin to see the content starting without needing to scroll down.

How to verify ECDSA and RSA certificates

I am going to run acme-tiny on a central webserver in order to get the certificates for my two Nginx reverse proxies issued. The newly created certificates are published over https and available to the reverse proxies via download. I want the Nginx servers to check the newly created certificates before replacing the old certificates with the new ones. For this purpose, I wrote the following bash script, which is run on each Nginx server. I would like to know whether I missed something or whether you have ideas for improvement. Or is there a better way to realise this? #!/bin/bash set -e # Commands for deriving the public keys: # openssl ec -in ecdsa.key -pubout > ecdsa_public_key.pem # openssl rsa -in rsa.key -pubout > rsa_public_key.pem curl -O https://example.org/ecdsa.pem curl -O https://example.org/intermediate.pem curl -O https://example.org/rsa.pem # Are the certificates not expired? # Have they (ecdsa.pem, rsa.pem) been recently issued (validity >= 80 days)? openssl x509 -checkend 6912000 -noout -in intermediate.pem openssl x509 -checkend 6912000 -noout -in ecdsa.pem openssl x509 -checkend 6912000 -noout -in rsa.pem # Do the private keys and certificates belong together? openssl x509 -in ecdsa.pem -pubkey | sed -n '/-----BEGIN PUBLIC KEY-----/,/-----END PUBLIC KEY-----/p' | cmp - ecdsa_public_key.pem openssl x509 -in rsa.pem -pubkey | sed -n '/-----BEGIN PUBLIC KEY-----/,/-----END PUBLIC KEY-----/p' | cmp - rsa_public_key.pem # Is the certificate chain valid? openssl verify -CAfile /etc/ssl/certs/ca-certificates.crt intermediate.pem openssl verify -CAfile intermediate.pem ecdsa.pem openssl verify -CAfile intermediate.pem rsa.pem # Are the certificates issued for the correct domain names? (openssl x509 -noout -subject -in ecdsa.pem | awk -F'CN=' '{print $2}' | awk -F'/' '{print $1}'; openssl x509 -noout -text -in ecdsa.pem | grep "^[[:space:]]*DNS:" | xargs | tr ' ' 'n' | grep ^DNS | sed 's/^DNS://' | sed 's/,$//')| sort | uniq | cmp - domains.txt (openssl x509 -noout -subject -in rsa.pem | awk -F'CN=' '{print $2}' | awk -F'/' '{print $1}'; openssl x509 -noout -text -in rsa.pem | grep "^[[:space:]]*DNS:" | xargs | tr ' ' 'n' | grep ^DNS | sed 's/^DNS://' | sed 's/,$//')| sort | uniq | cmp - domains.txt UPDATE 1: As I have stated I want to check every aspect of the certificate not just the validity of the certificate chain. It currently checks: the chains validity, whether private key and certificate match, whether the cert has been recently issued making replacement of the older cert necessary whether the cert has been issued for the desired domain names Therefore, it isn't a duplicate to the linked questions. And, I would like to know whether I have forgotten some check or whether there is space for improvement. Below is an update to the bash script. Beware I have not tested it thoroughly, yet. #!/bin/bash set -e # Execute the script: # ( cd /path_to_workdir && # su - james -c "./check_cert.sh https://www.example.org intermediate.pem ecdsa.pem ecdsa_pubkey.pem /etc/ssl/certs/ca-certificates.crt domains.txt pass.txt" && # su - james -c "./check_cert.sh https://www.example.org intermediate.pem rsa.pem rsa_pubkey.pem /etc/ssl/certs/ca-certificates.crt domains.txt pass.txt" && # cat ecdsa.pem intermediate.pem > /etc/nginx/ssl/ecdsa_bundle.pem ) && # cat rsa.pem intermediate.pem > /etc/nginx/ssl/rsa_bundle.pem ) && # /etc/init.d/nginx reload # Download URL, e.g. https://example.org URL=$1 # Intermediate certificate of certificate chain INTERMEDIATE=$2 # Issued certificate, e.g. ecdsa.pem CERT=$3 # Public key derived from private key via: # openssl ec -in ecdsa.key -pubout > ecdsa_pubkey.pem # openssl rsa -in rsa.key -pubout > rsa_pubkey.pem PUBKEY=$4 # ca-certificates file, e.g. /etc/ssl/certs/ca-certificates.crt CACERTS=$5 # Domains that the cert should cover DOMAINS=$6 # password-file.txt possible content: # machine example.org login james password H3Llo PASS=$7 # Download files if newer than local. if [[ $(curl -s -O --netrc-file "$PASS" -w "%{http_code}" -z "$CERT" "$URL/$CERT") -eq 304 ]]; then echo "No new certificate issued. Nothing to do!" exit 1 fi curl -s -O --netrc-file "$PASS" -z "$INTERMEDIATE" "$URL/$INTERMEDIATE" # Is the certificate chain valid? openssl verify -CAfile "$CACERTS" -untrusted "$INTERMEDIATE" "$CERT" # Do the private keys and certificates belong together? openssl x509 -in "$CERT" -pubkey | sed -n '/-----BEGIN PUBLIC KEY-----/,/-----END PUBLIC KEY-----/p' | cmp - "${PUBKEY}" # Has the Let's Encrypt certificate been recently issued (validity >= 80 days)? openssl x509 -checkend 6912000 -noout -in "$CERT" # Are the certificates issued for the correct domain names? (openssl x509 -noout -subject -in "$CERT" | awk -F'CN=' '{print $2}' | awk -F'/' '{print $1}'; openssl x509 -noout -text -in "$CERT" | grep "^[[:space:]]*DNS:" | xargs | tr ' ' 'n' | grep ^DNS | sed 's/^DNS://' | sed 's/,$//')| sort | uniq | cmp - "$DOMAINS" The code might be run via cronjob: 0 1 * * * /usr/local/bin/update_cert.sh >/dev/null 2>&1 The content of update_cert.sh might be: #!/bin/bash ( cd /path_to_workdir && su - james -c "./check_cert.sh https://www.example.org intermediate.pem ecdsa.pem ecdsa_pubkey.pem /etc/ssl/certs/ca-certificates.crt domains.txt pass.txt" && su - james -c "./check_cert.sh https://www.example.org intermediate.pem rsa.pem rsa_pubkey.pem /etc/ssl/certs/ca-certificates.crt domains.txt pass.txt" && cat ecdsa.pem intermediate.pem > /etc/nginx/ssl/ecdsa_bundle.pem ) && cat rsa.pem intermediate.pem > /etc/nginx/ssl/rsa_bundle.pem ) && /etc/init.d/nginx reload

List(Of ) like operation in macro

I have a macro that I am trying to get running a little more quickly. The intent of the macro is to merge multiple files into one. These files contain a unique ID for each item, some descriptive information about the item, and some measurement outcomes for each item. The measurement outcomes are what differ between the files.

In all the files, each item occupies a row, with the measurements in columns. No file lists all the items, but some items do appear in more than one file.

Currently, I iterate through the files and either use the data to update an existing row (for the items in a file that's already been processed), or create a new row if the item hasn't appeared in any previous file.

The place I'm losing a good chunk of time, especially on the later files, is finding the row for an item I've already added to the unified list, so that I can add the new measurement values to the appropriate column(s).

Function MMFProcessor(sfol As String, ifn As String, x As Integer, os As Worksheet, NPU As String, Prods As String, sw As StatWin, PM As String, _
FlgMeas() As String, m As Long, MKO As String, OName As String, Optional Ambetter As Boolean = False) As Variant()
'
Dim src As Workbook 'workbook containing the info to copy to unified list
Set src = Workbooks.Open(sfol & "" & ifn & Right(Year(Now() - 25), 2) & "_.xlsx")
Dim mks As String
Dim mgc As String 
Dim sm As String
Dim FMC As Boolean
FMC = False 'want to only check that the filled length of FlgMeas & FMCol match once
Dim ret As Boolean 'whether the function completed successfully
ret = True 'easier to ID failures rather than only setting to True on success
Dim RArr(3) As Variant 'return
Dim fnd As Boolean
Dim y As Integer

'...(non-relevant code)

    'Iterate through the rows to output data
    Dim k As Long 'Source row being worked with
    Dim OutF As Boolean 'used to stop loop for flag column setting after column is found & set
    k = 2
    Do While src.Worksheets(1).Range("A" & k).Value <> "" And ret
        'Product match?
        If InStr(1, LCase(Prods), "|" & LCase(src.Worksheets(1).Range(mgc & k).Value) & "|") > 0 Or _
            (Ambetter And InStr(1, LCase(src.Worksheets(1).Range(mgc & k).Value), "ambetter") > 0) Then
            'Check if the item is new
            If InStr(1, PM, "|" & src.Worksheets(1).Range(mks & k).Value & "|") = 0 Then
                'New add it to PM
                PM = PM & "|" & src.Worksheets(1).Range(mks & k).Value & "|"

                'Output the descriptive info
                For y = 0 To x
                    'UnMapped column?
                    If ColDict(y, 1) <> "" Then
                        'Output the value
                        os.Range(ColDict(y, 0) & m).Value = src.Worksheets(1).Range(ColDict(y, 1) & k).Value
                    End If 'else the cell should be left blank, which is the default
                Next

                'Set the appropriate flag column
                Call FlagSet(FlgMeas(), src, os, sm, k, m, sw, OName)

                'Increment m
                m = m + 1

            Else
                'Find the item's row (in general it will be the last row filled, so we'll decrement from the end of the list rather then increment from the start)
                Dim n As Long
                n = m - 1
                fnd = False
                Do While n > 1 And fnd = False
                    If os.Range(MKO & n).Value = src.Worksheets(1).Range(mks & k).Value Then
                        'Set the appropriate flag column
                        Call FlagSet(FlgMeas(), src, os, sm, k, n, sw, OName)

                        fnd = True
                    Else
                        n = n - 1
                    End If
                Loop

                If Not fnd Then
                    'post notice if we haven't already for this item and this file
                    If OldOName <> OName Then
                        'Update OldOName and clear INotFnd
                        OldOName = OName
                        INotFnd = ""
                    End If

                    'Check if item is in INotFnd (if we've changed files INotFnd will be empty)
                    If InStr(1, INotFnd, "|" & src.Worksheets(1).Range(mks & k).Value & "|") = 0 Then
                        Call Err("Item: " & src.Worksheets(1).Range(mks & k).Value & " is noted as already being present in the " & OName & " list, but" _
                            & " that row could not be located to update the item's measurement values, meaning one or more of the values will be incorrect" _
                            & ". Please be sure to make this change manually.", sw)
                        INotFnd = INotFnd & "|" & src.Worksheets(1).Range(mks & k).Value & "|"
                    End If 'else no need to repeat for same item
                End If
            End If
        End If 'non-<Products> items don't get reported

        k = k + 1
    Loop
End If 'else the arrays didn't match up and we've already notified the user

'...(more irrelevant code)

FlgMeas() is an array that maps the measurement columns' names to the column that measure should be output to; mks is the column letter of the column that has the item IDs

As I mentioned at the beginning, this works, but it will sometimes have to iterate back through over 20k rows to find the right one. Currently that leaves the merge taking over 2 hrs, and I've just been directed to include more files (thus why I'm wanting to shave down the run time).

So what I was hoping to get was something that works like VB Lists, where I could look-up a value (in this case the row to output to) based on a value (the ID) without having to iterate explicitly.

Failing any such thing existing in native VBA, would it be faster for me to maintain PM (the list of previously output IDs) as a 2D array, holding IDs & row #s, and iterate through that rather than the actual rows?

Thanks in advance!

res.json Can't set headers after they are sent

I'm learning node Js and i'm trying to do a simple subscribe/log_in app. I'm having issue with res.json not working as intended.

Got this error when i'm trying to subscribe : Can't set headers after they are sent

This is my server side script :

var express = require('express');
var swig = require('swig');
var ent = require('ent');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');

var app = express();

// Environnement
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/public", express.static(__dirname + "/public"));
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(session({
    secret: 'poussixthetruefighteroftheparadise',
    saveUninitialized: true,
    resave: true
}));

//MongoDB
var db = mongoose.connect('mongodb://127.0.0.1:27017/maBase');
var userSchema = new mongoose.Schema({
    login:  String,
    mail: String,
    password: String
});
var user = db.model('user', userSchema)

// variables globales
var state;




// Page Principale
app.get('/', function(req,res){

    if (req.session.user) {
        res.render('accueil.html',{});
    } else {
        res.redirect('/connection');
    }

});

// Page connection
app.route('/connection')
    .get(function(req, res) {

        res.render('index.html',{});

        if (req.session.state) {
            res.json({state: req.session.state});
        }

    })
    .post(function(req, res) {

        user.find({login: req.body.login, password: req.body.password}).limit(1).exec(function (err, users) {

            if (err) { console.log(err) };

            if (!users.length) {

                console.log('connection pas ok');

                res.json({state: '5'});

            }
            else {

                console.log('connection ok');
                res.redirect('/');

            }

        });

    });


// Ajouter Utilisateur
app.post('/connection/ajouter', function(req,res){

    var login = req.body.login;
    var mail = req.body.mail;

    user.find({$or: [{login: login}, {mail: mail}]}).limit(1).exec(function (err, users) {

        if (err) { console.log(err) };

        if (!users.length) {

            console.log('login et mail ok');

            if (req.body.password == req.body.password2) {

                if (req.body.password.length > 6) {

                    var values = new user({
                            login: ent.encode(req.body.login),
                            mail: ent.encode(req.body.mail),
                            password: ent.encode(req.body.password)
                    });

                    values.save(function(err, values) {

                        if (err) return console.error(err);

                        console.log('utilisateur enregistré');

                        req.session.state = '6';
                        res.redirect('/connection');

                    });

                } else {

                    console.log('Mot de passe trop court');

                    req.session.state = '3';
                    res.redirect('/connection');

                }


            } else {

                console.log('mot de passe différent');

                req.session.state = '4';
                res.redirect('/connection');

            }

        }

        else {

            console.log('login ou mail déja utilisé');

            if (users[0].mail == mail) {

                console.log('mail déja utilisé');
                req.session.state = '2';
                res.redirect('/connection');

            } else {

                console.log('login déja utilisé');
                req.session.state = '1';
                res.redirect('/connection');

            }

            console.log(users);

        }

    });

});




app.listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

And my client side script :

<html>
<head>
    <title>test</title>
    <link rel="stylesheet" href="public/css/reset.css">
    <link rel="stylesheet" href="public/css/connection.css">
</head>
<body>

    <div id="content">

        <a href="http://localhost:3000"><img src="public/images/icone.jpg" alt="gatsbill"></a>

        <div id="wrap">

            <div id="espacehaut"></div>
            <div class="click" id="con" style="display: block;">Se connecter</div>
            <div class="click" id="sub" style="display: none;">S'inscrire</div>

            <div id="connection" style="display: none;">
                <div id="message1" class="message" style="display: none;"></div>
                <form action="/connection/" method="post" id="form_connection">
                    <input type="text" name="login" id="login" placeholder="Login" value="" required="" autofocus="">
                    <input type="password" name="password" id="password" placeholder="Password" required="">
                    <input type="submit" name="submit" value="Connect">
                </form>
            </div>

            <div id="subscribe" style="">
                <p id="p">Pour vous inscrire,<br> Veuillez remplir les champs ci-dessous</p>
                <div id="message2" class="message" style="display: none;"></div>
                <form action="/connection/ajouter/" method="post" id="form_inscription">
                    <input type="text" name="login" placeholder="Login" value="" required="" autofocus="">
                    <input type="email" name="mail" placeholder="Email" value="" required="">
                    <input type="password" name="password" placeholder="Password" required="">
                    <input type="password" name="password2" placeholder="Password" required="">
                    <input type="submit" name="submit" value="Create account">
                </form>
            </div>

            <div id="espacebas"></div>

        </div>
    </div>

    <!-- Script -->
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript" src="public/js/connection.js"></script>
    <script>

        $.getJSON( "http://localhost:3000/connection", function(data){
            if( data.state ) {
                state = parseInt(data.state);
                switch (state) {
                    case 1:
                        formulaire();
                        $("#message2").text("login déja utilisé");
                        break;

                    case 2:
                        formulaire();
                        $("#message2").text("mail déja utilisé");
                        break;

                    case 3:
                        formulaire();
                        $("#message2").text("Mot de passe trop court");
                        break;

                    case 4:
                        formulaire();
                        $("#message2").text("mot de passe différent");
                        break;

                    case 5:
                        connect();
                        $("#message1").text("connection pas ok");
                        break;

                    case 6:
                        connect();
                        $("#message1").text("vous pouvez maintenant vous connecter");
                        break;

                }
            }
        });

    </script>

</body>
</html>

When i'm trying to subscribe with two different password this is what I have :

A white page with only this :

{"state":"4"}

And of course this error in node Js console: Can't set headers after they are sent

angular js how to use existing json object

I am converting my existing project to angularJs. There is an Json object I that I keep update on form submit.

autoquoteDTO.js

$.getAutoQuoteObject=function(){var autoQuoteObject=new autoQuote();autoQuoteObject.DriverVehicleInfo=new DriverVehicleInfo();autoQuoteObject.DriverVehicleInfo.Vehicles=[];autoQuoteObject.DriverVehicleInfo.Drivers=[];autoQuoteObject.ApplicationInfo=new ApplicationInfo();autoQuoteObject.ApplicationInfo.Discount=new Discount();autoQuoteObject.ApplicationInfo.GeneralPartyInfo=new GeneralPartyInfo();autoQuoteObject.ApplicationInfo.GeneralPartyInfo.ContactInfo=new Contact();autoQuoteObject.ApplicationInfo.MostRecentInsurance=new MostRecentInsurance();autoQuoteObject.RequestedCoverage=new RequestedCoverage();autoQuoteObject.RequestedCoverage.PolicyCoverage=new PolicyCoverage();autoQuoteObject.RequestedCoverage.PolicyCoverage.Coverages=[];autoQuoteObject.RequestedCoverage.VehicleCoverage=[];autoQuoteObject.SessionInfo=new SessionInfo();return autoQuoteObject;}
function autoQuote(){this.DriverVehicleInfo=null;this.ApplicationInfo=null;this.RequestedCoverage=null;this.SessionInfo=null;}
var DriverVehicleInfo=function(){this.Drivers=[];this.Vehicles=[];this.DriverVehicleUsages=[];};var Driver=function(){this.ID=null,this.PersonInfo=null,this.DriverRelationshipToApplicant=null,this.DriverRelationshipToApplicantCd=null,this.DriverLicense=null,this.DriverDetails=[],this.Incident=null,this.IsValid=false};var PersonInfo=function(){this.FirstName=null,this.Initial=null,this.LastName=null,this.Suffix=null,this.SSN=null,this.GenderCd=null,this.BirthDate=null,this.MaritalStatusCd=null,this.OccupationClassCd=null,this.YearsOccupation=null,this.HighestEducation=null,this.AgeInYears=0,this.SpouseLicenseStatus=null};var DriverLicense=function(){this.AgeLicense=null,this.USLicenseStatus=null,this.DriverLicenseNumber=null,this.StateProvCd=null};var DriverDetail=function(){this.DriverDetailCd=null,this.DriverDetailValue=null,this.DriverDetailDate=null};var Incident=function(){this.ClaimAccidentsCount=null,this.ViolationsCount=null,this.HasLicenseBeenRevoked=null,this.LicenseSuspensionRevokedDate=null,this.HasRequiredCourtOrderedFinancial=null,this.ClaimAccidents=[],this.Violations=[],this.DUIs=[]};var DUI=function(){this.DateOfDUI=null,this.OtherValues=[]};var ClaimAccident=function(){this.Id=null,this.ClaimAccidentCd=null,this.displayText=null,this.ClaimAccidentDate=null,this.DateDisplayText=null,this.Comprehensive=null,this.Collision=null,this.RentalReimbursement=null,this.MedicalPayment=null,this.PayToOtherParty=null,this.IsInjury=null,this.IsPropertyDamage=null};var Violation=function(){this.Id=null,this.ViolationCd=null,this.ViolationDate=null,this.displayText=null};var Vehicle=function(){this.ID=null,this.VehicleHaveVin=false,this.VehicleIdentificationNumber=null,this.VehicleYear=null,this.VehicleMake=null,this.VehicleModel=null,this.VehicleSubModel=null,this.AntiLockBrakeCd=null,this.AntiTheftDeviceCd=null,this.VehicleUseCd=null,this.NumDaysDrivenPerWeek=null,this.DistanceOneWay=null,this.EstimatedAnnualDistance=null,this.OwnershipCd=null,this.RegistrationStateProvCd=null,this.VehIdentificationNumber=null,this.IsCustomizedOrAltered=null,this.OriginalVehicleCost=null,this.IsValid=false,this.VehicleType=null,this.VehicleVinStub=null,this.ShowVehicleAntiLockBrakeInfo=false,this.VehicleCost=null,this.ShowVehicleCost=false,this.DaytimeLights=null};var DriverVehicleUsage=function(){this.DriverIDRef=null,this.VehicleIDRef=null,this.Usage=null};var ApplicationInfo=function(){this.GeneralPartyInfo=null,this.Discount=null,this.MostRecentInsurance=null,this.ConsumerContactAuth=null,this.ConsumerInfoAuthorization=null,this.ConsumerContactMobileAuth=null};var GeneralPartyInfo=function(){this.MainApplicantDriverIDRef=null,this.Address=null,this.PreviousAddress=null,this.ContactInfo=null,this.ResidenceInfo=null,this.ListedVehiclesRegisteredTo=null,this.CreditScore=0};var AddressInfo=function(){this.Address=null,this.City=null,this.State=null,this.PostalCode=null,this.County=null};var PreviousAddress=function(){this.Address=null,this.City=null,this.State=null,this.PostalCode=null,this.County=null};var Contact=function(){this.Phones=[],this.Emails=[]};var Email=function(){this.EmailTypeCd=null,this.EmailAddress=null};var Phone=function(){this.PhoneTypeCd=null,this.PhoneNumber=null};var Residence=function(){this.LengthAtCurrentAddressCd=null,this.ResidenceTypeCd=null,this.NumberDriversInHouseHold=null,this.VehiclesRegistedToInsured=null,this.DriverResidentsFromFL=null,this.CityLimits=null};var Discount=function(){this.ResidentialInsurancePolicy=null,this.OwnBoat=null,this.OwnMotorCycle=null,this.IsAAAMember=null};var MostRecentInsurance=function(){this.HasAutoInsurance=null,this.InsuranceCompanyName=null,this.CurrentInsurancePaying=null,this.LengthWithCurrentInsuranceCd=null,this.BodilyInjuryLiabilityLimit=null,this.LengthContinuouslyInsuredCd=null,this.ExpirationDate=null,this.InsuranceCanceledForNonPay=null,this.ClaimDeniedDueToFraud=null};var RequestedCoverage=function(){this.EffectiveDate=null,this.StateCd=null,this.PolicyCoverage=null,this.VehiclesCoverage=[]};var PolicyCoverage=function(){this.Coverages=[]};var Coverage=function(){this.CoverageCd=null,this.CoverageValue=null};var VehicleCoverage=function(){this.IsValid=false,this.VehicleIDRef=null,this.Coverages=[]};var SessionInfo=function(){this.SessionId='',this.SecurityToken='',this.Zip='',this.StateCode='',this.PageName='',this.PageTheme='',this.CarrierId=-1,this.ReturnedCarrierTypes=null,this.CoveragePackage='',this.UseExistingSession=false,this.QuoteStatus='',this.SID=-1,this.SRC=null,this.SRC_QCP=null,this.Referral=null,this.ClientIP=null,this.BrowserType=null,this.CLK=0,this.QTR='',this.CCID='',this.AFF='',this.PreviousSessionId='',this.IgnoreErrors=false,this.RetrieveSource='',this.PreviousPageName=''}

prapareJson.js

var prepareAutoQuoteDTO = {
    postAutoQuoteObj         : $.getAutoQuoteObject(),  
    initializeDriverObj: function()
    {
        var driverLocObj           = new Driver();
        driverLocObj.PersonInfo    = new PersonInfo();
        driverLocObj.DriverLicense = new DriverLicense();
        driverLocObj.Incident      = new Incident();
        return driverLocObj;
    },

    initializeAppInfo: function()
    {
        var appInfoLocObj           = new ApplicationInfo();
        appInfoLocObj.Discount      = new Discount();
        return appInfoLocObj;

    },
    /*
    * Initialize Vehicle object for autoQuoteDTO.js
    */
    initializeVehicleObj: function()
    {
        var vehicleLocObj = new Vehicle();
        return vehicleLocObj;
    },

    rc1Step1DTO: function()
    {
       /*
        * store session info
        */
        var emailId = $('#save_quote_email').val();
        if (typeof emailId  !== "undefined" && emailId && emailId != '' && emailId != 'Email Address')
        {
            var email           = new Email();
            email.EmailTypeCd   = 'PRIMARY';
            email.EmailAddress  = emailId;
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo = this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
            this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
        }
};

update json on user event

prepareAutoQuoteDTO.rc1Step1DTO();

Below is my angular js code

 (function(){
    "use strict";
    angular
    .model("autoQuote")
    .controller("prepareDTO","prepareDTO")
    .controller("postDTO","postDTO");
        /*
         * Call actions on page load
         */
    var init = function () {
                 prepareDTO();    
        }
        init();

        /*
         * prepare DTO with form elements.
         */
        function prepareDTO()
    {
         var vm = this;
         vm.postAutoQuoteObj = [];   
    }

        /*
         * post DTO on form submit and page onload.
         */
        function postDTO()
        {

        }     

 });

Here want to achieve things in prepareDTO funtion.

Looking for suggestions to achieve this. Plunker of my complete code

http://plnkr.co/edit/VJKrDRMJY3Q73bsCgVwX?p=preview what I want to achieve here is if step1 form is submitted rc1Step1DTO should be called and json should save that data.

I can remove this file and everything can be achived in angular js. but stuck how to do that in angularjs.

Android SQLite database doesnot Update and Delete

This is mainactivity which provides the user Input

public class Welcome extends AppCompatActivity{
private DBMANAGER_person dbmanager_person;
private ListView listView;
private SimpleCursorAdapter adapter;

final String [] from = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE, MyDB.COLUMN_HEIGHT , MyDB.COLUMN_WEIGHT};
final int [] to = new int[]{R.id.nameTV,R.id.ageTV,R.id.heightTV,R.id.weightTV};



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    dbmanager_person = new DBMANAGER_person(this);
    dbmanager_person.open();

    Cursor cursor = dbmanager_person.fetch();

    listView = (ListView) findViewById(R.id.list_view);
    listView.setEmptyView(findViewById(R.id.emptyTV));

    adapter = new SimpleCursorAdapter(this, R.layout.person, cursor, from, to,0);
    adapter.notifyDataSetChanged();

    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView idTextView = (TextView)view.findViewById(R.id.idTV);
            TextView nameTextView = (TextView) view.findViewById(R.id.nameTV);
            TextView ageTextView = (TextView) view.findViewById(R.id.ageTV);
            TextView heightTextView = (TextView) view.findViewById(R.id.heightTV);
            TextView weightTextView = (TextView) view.findViewById(R.id.weightTV);

            String iD = idTextView.getText().toString();
            String name = nameTextView.getText().toString();
            String age = ageTextView.getText().toString();
            String height = heightTextView.getText().toString();
            String weight = weightTextView.getText().toString();

            Intent intent = new Intent(getApplicationContext(), Modiffy_person_Details.class);
            intent.putExtra("_id",iD);
            intent.putExtra("name", name);
            intent.putExtra("age", age);
            intent.putExtra("height", height);
            intent.putExtra("weight", weight);

            startActivity(intent);


        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.add_person,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if(id == R.id.add){
        Intent intent = new Intent(this,Add_people.class);
        startActivity(intent);

    }else if (id == R.id.logout){
        Intent backToHome = new Intent(this,MainActivity.class);
        startActivity(backToHome);
    }

    return super.onOptionsItemSelected(item);
}

}

This is Add_prople class

public class Add_people extends AppCompatActivity implements View.OnClickListener { private EditText nameEditText; private EditText ageEditText; private EditText heightEditText; private EditText weightEditText;

private Button save;
private DBMANAGER_person dbmanager_person;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setTitle("Add People");

    setContentView(R.layout.activity_add_people);

    nameEditText = (EditText)findViewById(R.id.nameET);
    ageEditText = (EditText)findViewById(R.id.ageET);
    heightEditText = (EditText)findViewById(R.id.heightET);
    weightEditText = (EditText)findViewById(R.id.weightET);

    save = (Button)findViewById(R.id.saveBtn);

    dbmanager_person = new DBMANAGER_person(this);
    dbmanager_person.open();
    save.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.saveBtn:
            final String name = nameEditText.getText().toString();
            final String age = ageEditText.getText().toString();
            final String height = heightEditText.getText().toString();
            final String weight = weightEditText.getText().toString();

            dbmanager_person.insert(name,age,height,weight);

            Intent main = new Intent(this,Welcome.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(main);
            break;

    }

}

}

This is DBMANAGER_person class where the CRUD operation works

This is the Modiffy_person_Details class where user can Update and Delete their information

public class DBMANAGER_person {
private SQLiteDatabase database;
private MyDB myDB;
private Context context;

public DBMANAGER_person(Context context) {
    this.context = context;
}

public DBMANAGER_person open() throws SQLiteException{
    myDB = new MyDB(context);
    database = myDB.getWritableDatabase();
    return this;
}

public void close(){
    myDB.close();
}
public void insert(String name,String age,String height,String weight){
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDB.COLUMN_NAME,name);
    contentValues.put(MyDB.COLUMN_AGE,age);
    contentValues.put(MyDB.COLUMN_HEIGHT,height);
    contentValues.put(MyDB.COLUMN_WEIGHT,weight);
    database.insert(MyDB.TABLE_NAME,null,contentValues);
}

public Cursor fetch(){
    String[] columns  = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE , MyDB.COLUMN_HEIGHT, MyDB.COLUMN_WEIGHT};
    Cursor cursor = database.rawQuery( "select rowid _id,* from "+MyDB.TABLE_NAME, null);
    cursor.moveToFirst();
    return cursor;
}

public int update(long id, String name, String age, String height, String weight){
    ContentValues contentValues = new ContentValues();
    contentValues.put(MyDB.COLUMN_NAME,name);
    contentValues.put(MyDB.COLUMN_AGE,age);
    contentValues.put(MyDB.COLUMN_HEIGHT,height);
    contentValues.put(MyDB.COLUMN_WEIGHT,weight);
    int i = database.update(MyDB.TABLE_NAME,contentValues,MyDB.COLUMN_ID + " = "+id,null);
    return i;
}

public void delete(long id){
    database.delete(MyDB.TABLE_NAME, MyDB.COLUMN_ID + "="+ id,null);
}

}

public class Modiffy_person_Details extends AppCompatActivity implements View.OnClickListener{ private EditText nameField; private EditText ageField; private EditText heightField; private EditText weightField;

private Button update;
private Button delete;

private long _id;
private DBMANAGER_person dbmanager_person;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("Modify Record");
    setContentView(R.layout.activity_modiffy_person__details);

    dbmanager_person = new DBMANAGER_person(this);
    dbmanager_person.open();

    nameField = (EditText)findViewById(R.id.nameEditText);
    ageField = (EditText)findViewById(R.id.ageEditText);
    heightField = (EditText)findViewById(R.id.heightEditText);
    weightField = (EditText)findViewById(R.id.weightEditText);

    update = (Button)findViewById(R.id.update_btn);
    delete = (Button)findViewById(R.id.delete_btn);

    Intent intent = getIntent();
    String ID = intent.getStringExtra("_id");
    String name = intent.getStringExtra("name");
    String age = intent.getStringExtra("age");
    String height = intent.getStringExtra("height");
    String weight = intent.getStringExtra("weight");

    String check_ID = ID;
    if(!check_ID.equals("")) {

        _id = Long.parseLong(ID);
    }/*else{
        Toast.makeText(getApplicationContext(),"There is no id",Toast.LENGTH_LONG).show();
    }*/



        nameField.setText(name);
        ageField.setText(age);
        heightField.setText(height);
        weightField.setText(weight);





    update.setOnClickListener(this);
    delete.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.update_btn:
            String na = nameField.getText().toString();
            String ag = ageField.getText().toString();
            String hei = heightField.getText().toString();
            String wei = weightField.getText().toString();

            dbmanager_person.update( _id , na , ag,hei,wei);
            this.returnHome();
            break;
        case R.id.delete_btn:
            dbmanager_person.delete(_id);
            this.returnHome();
            break;
    }

}

public void returnHome(){
    Intent home_intent = new Intent(getApplicationContext(),Welcome.class)
            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(home_intent);
}

}

My problem is whenever i want to update or delete my information it does not work.

org.hibernate.HibernateException: No Session found for current thread 5

I know this problem is asked a lot but I am stuck. I am basing my project off of this tutorial: http://www.cavalr.com/blog/Spring_3_and_Annotation_Based_Hibernate_4_Example

This is my root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">

  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <property name="initialPoolSize" value="1" />
    <property name="minPoolSize" value="1" />
    <property name="maxPoolSize" value="20" />
  </bean>

  <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath:db.properties</value>
      </list>
    </property>
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.joe.recipes.data" />
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>

    </property>
  </bean>

  <!-- Enables the Hibernate @Transactional programming model -->
  <tx:annotation-driven transaction-manager="transactionManager"/>

  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
  </bean>
</beans>

This is my servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context.xsd">

  <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
  <context:component-scan base-package="com.joe.recipes" />
  <!-- Enables the Spring MVC @Controller programming model -->
  <mvc:annotation-driven />

  <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
  <resources mapping="/resources/**" location="/resources/" />

  <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
  <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
  </beans:bean>

</beans:beans>

This is my AbstractDaoImpl

public abstract class AbstractDaoImpl<E, I extends Serializable> implements AbstractDao<E,I> {

    private Class<E> entityClass;

    protected AbstractDaoImpl(Class<E> entityClass) {
        this.entityClass = entityClass;
    }

    @Autowired
    private SessionFactory sessionFactory;

    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    @Override
    public E findById(I id) {
        return (E) getCurrentSession().get(entityClass, id);
    }

    @Override
    public void saveOrUpdate(E e) {
        getCurrentSession().saveOrUpdate(e);
    }

    @Override
    public void delete(E e) {
        getCurrentSession().delete(e);
    }

    @Override
    public List findByCriteria(Criterion criterion) {
        Criteria criteria = getCurrentSession().createCriteria(entityClass);
        criteria.add(criterion);
        return criteria.list();
    }
}

This is my RecipeDaoImpl class

@Repository
public class RecipeDaoImpl extends AbstractDaoImpl<Recipe, String> implements RecipeDao {

    protected RecipeDaoImpl() {
        super(Recipe.class);
    }

    @Override
    public boolean saveRecipe(Recipe r) {
        return saveRecipe(r);
    }

    @Override
    public Recipe getRecipe(String recipeId) {
        return findById(recipeId);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Recipe> findRecipes(String keyword) {
        return findByCriteria( Restrictions.and( Restrictions.like("name", keyword, MatchMode.ANYWHERE),
            Restrictions.like("keywords", keyword, MatchMode.ANYWHERE) ) );
    }
}

This is my RecipeServiceImpl class

@Service("recipeService")
@Transactional(readOnly = true)
public class RecipeServiceImpl implements RecipeService {
    @Autowired
    private RecipeDao recipeDao;

    @Override
    @Transactional(readOnly = false)
    public boolean saveRecipe(Recipe r) {
        return recipeDao.saveRecipe(r);
    }

    @Override
    public Recipe getRecipe(String recipeId) {
        return recipeDao.getRecipe(recipeId);
    }

    @Override
    public List<Recipe> findRecipes(String keyword) {
        return recipeDao.findRecipes(keyword);
    }
}

This is my RecipeController

/**
 * Handles requests for the application home page.
 */
@Controller
public class RecipeController {

    private static final Logger logger = LoggerFactory.getLogger(RecipeController.class);

    @Autowired
    private RecipeService recipeService;

    /**
     * Adds recipes to the DB
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Locale locale, Model model) {
        return "add";
    }

    /**
     * Searches for recipes
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public String search(@RequestParam(value="keyword", required=true) String keyword, Model model) {

        List<Recipe> recipes = recipeService.findRecipes(keyword);
        System.out.println( "Results:"+ recipes.size() );
        return "results";
    }

    /**
     * Logs in the user
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Locale locale, Model model) {

        return "login";
    }
}

I've tried putting the @Transactional on the RecipeDaoImpl class and the AbstractDaoImpl class and neither worked.

EDIT: I fixed this by catching the exception and opening a new one:

public Session getCurrentSession() {
    Session session = null;
    try { 
        session = sessionFactory.getCurrentSession();
    } catch ( HibernateException he ) {
        session = sessionFactory.openSession();
    }
    return session;
}

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Consider the main axis and cross axis of a flex container:

enter image description here                                                                                                                        Source: W3C

To align flex items along the main axis there is one property: justify-content

To align flex items along the cross axis there are three properties: align-content, align-items and align-self.

In the image above, the main axis is horizontal and the cross axis is vertical. These are the default directions of a flex container. However, these directions can be easily interchanged with the flex-direction property.

/* main axis is horizontal, cross axis is vertical */
flex-direction: row;
flex-direction: row-reverse;

/* main axis is vertical, cross axis is horizontal */    
flex-direction: column;
flex-direction: column-reverse;

(The cross axis is always perpendicular to the main axis.)

My point in describing how the axes' work is that there doesn't seem to be anything special about either direction. Main axis, cross axis, they're both equal in terms of importance and flex-direction makes it easy to switch back and forth.

So why does the cross axis get two additional alignment properties?

Why are align-content and align-items consolidated into one property for the main axis?

Why does the main axis not get a justify-self property?


Scenarios where these properties would be useful:

  • placing a flex item in the corner of the flex container
    #box3 { align-self: flex-end; justify-self: flex-end; }

  • making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)

    Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly (the flexbox way) to different screen sizes.

  • in a row of three flex items, affix the middle item to the center of the container (justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).

    Note that values space-around and space-between on justify-content property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).


There is no mention of justify-self or justify-items in the flexbox spec.

However, in the CSS Box Alignment Module, which is the W3C's unfinished proposal to establish a common set of alignment properties for use across all box models, they have this:

enter image description here                                                                                                                         Source: W3C

You'll notice that justify-self and justify-items are being considered... but not for flexbox.

(Interestingly, contrary to the table illustration, the actual definition of justify-items in this document says it applies to flex containers.)


I'll end by reiterating the main question:

Why are there no "justify-items" and "justify-self" properties?

samedi 25 juin 2016

How to format the list items of QCompleter's popup list properly?

I want to investigate how to make a small user interface in which a user can type some letters and gets some suggestions based on a given data source (list here) which makes searches easier. For this purpose i am using Qt's QCompleter class.

In the matching elements the typed letters shall be highlighted with HTML like the example in the code below: Au<b>st</b>ria. Finally i merged some SO answers (see How to make item view render rich (html) text in Qt) and tutorials to a small standalone module:

from PySide import QtCore, QtGui

class HTMLDelegate(QtGui.QStyledItemDelegate):
    """ From: http://stackoverflow.com/a/5443112/1504082 """

    def paint(self, painter, option, index):
        options = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(options, index)
        if options.widget is None:
            style = QtGui.QApplication.style()
        else:
            style = options.widget.style()

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(option.rect.width())

        options.text = ""
        style.drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter)

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()

        # Highlighting text if item is selected
        # if options.state & QtGui.QStyle.State_Selected:
        #     ctx.palette.setColor(QtGui.QPalette.Text,
        #                          options.palette.color(QtGui.QPalette.Active,
        #                                                QtGui.QPalette.HighlightedText))

        textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText,
                                        options)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)
        painter.restore()

    def sizeHint(self, option, index):
        options = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(options, index)
        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())
        return QtCore.QSize(doc.size().width(), doc.size().height())


class CustomQCompleter(QtGui.QCompleter):
    """ Implement "contains" filter mode as the filter mode "contains" is not
    available in Qt < 5.2
    From: http://stackoverflow.com/a/7767999/1504082 """

    def __init__(self, parent=None):
        super(CustomQCompleter, self).__init__(parent)
        self.local_completion_prefix = ""
        self.source_model = None
        self.delegate = HTMLDelegate()

    def setModel(self, model):
        self.source_model = model
        super(CustomQCompleter, self).setModel(self.source_model)

    def updateModel(self):
        local_completion_prefix = self.local_completion_prefix

        # see: http://doc.qt.io/qt-4.8/model-view-programming.html#proxy-models
        class InnerProxyModel(QtGui.QSortFilterProxyModel):
            def filterAcceptsRow(self, sourceRow, sourceParent):
                # model index mapping by row, 1d model => column is always 0
                index = self.sourceModel().index(sourceRow, 0, sourceParent)
                source_data = self.sourceModel().data(index, QtCore.Qt.DisplayRole)
                # performs case insensitive matching
                # return True if item shall stay in th returned filtered data
                # return False to reject an item
                return local_completion_prefix.lower() in source_data.lower()

        proxy_model = InnerProxyModel()
        proxy_model.setSourceModel(self.source_model)
        super(CustomQCompleter, self).setModel(proxy_model)
        # @todo: Why to be set here again?
        self.popup().setItemDelegate(self.delegate)

    def splitPath(self, path):
        self.local_completion_prefix = path
        self.updateModel()
        return ""


class AutoCompleteEdit(QtGui.QLineEdit):
    """ Basically from:
    http://doc.qt.io/qt-5/qtwidgets-tools-customcompleter-example.html
    """

    def __init__(self, list_data, separator=' ', addSpaceAfterCompleting=True):
        super(AutoCompleteEdit, self).__init__()
        # settings
        self._separator = separator
        self._addSpaceAfterCompleting = addSpaceAfterCompleting
        # completer
        self._completer = CustomQCompleter(self)
        self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self._completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)

        self.model = QtGui.QStringListModel(list_data)
        self._completer.setModel(self.model)

        # connect the completer to the line edit
        self._completer.setWidget(self)
        # trigger insertion of the selected completion when its activated
        self.connect(self._completer,
                     QtCore.SIGNAL('activated(QString)'),
                     self._insertCompletion)

        self._ignored_keys = [QtCore.Qt.Key_Enter,
                              QtCore.Qt.Key_Return,
                              QtCore.Qt.Key_Escape,
                              QtCore.Qt.Key_Tab]

    def _insertCompletion(self, completion):
        """
        This is the event handler for the QCompleter.activated(QString) signal,
        it is called when the user selects an item in the completer popup.
        It will remove the already typed string with the one of the completion.
        """
        stripped_text = self.text()[:-len(self._completer.completionPrefix())]

        extra_text = completion  # [-extra:]
        if self._addSpaceAfterCompleting:
            extra_text += ' '
        self.setText(stripped_text + extra_text)

    def textUnderCursor(self):
        text = self.text()
        textUnderCursor = ''
        i = self.cursorPosition() - 1
        while i >= 0 and text[i] != self._separator:
            textUnderCursor = text[i] + textUnderCursor
            i -= 1
        return textUnderCursor

    def keyPressEvent(self, event):
        if self._completer.popup().isVisible():
            if event.key() in self._ignored_keys:
                event.ignore()
                return
        super(AutoCompleteEdit, self).keyPressEvent(event)
        completionPrefix = self.textUnderCursor()
        if completionPrefix != self._completer.completionPrefix():
            self._updateCompleterPopupItems(completionPrefix)
        if len(event.text()) > 0 and len(completionPrefix) > 0:
            self._completer.complete()
        if len(completionPrefix) == 0:
            self._completer.popup().hide()

    def _updateCompleterPopupItems(self, completionPrefix):
        """
        Filters the completer's popup items to only show items
        with the given prefix.
        """
        self._completer.setCompletionPrefix(completionPrefix)
        # self._completer.popup().setCurrentIndex(
        #     self._completer.completionModel().index(0, 0))


if __name__ == '__main__':
    def demo():
        import sys
        app = QtGui.QApplication(sys.argv)
        values = ['Germany',
                  'Au<b>st</b>ria',
                  'Switzerland',
                  'Hungary',
                  'The United Kingdom of Great Britain and Northern Ireland']
        editor = AutoCompleteEdit(values)
        window = QtGui.QWidget()
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(editor)
        window.setLayout(hbox)
        window.show()

        sys.exit(app.exec_())

    demo()

My problem is the suggestion of user Timo in the answer http://stackoverflow.com/a/5443112/1504082:

After line: 'doc.setHtml(options.text)', you need to set also doc.setTextWidth(option.rect.width()), otherwise the delegate wont render longer content correctly in respect to target drawing area. For example does not wrap words in QListView.

So i did this to avoid cropping of long text in the completer's popup. But i get the following output: Where does this vertical margin come from?

Where does this additional vertical margin come from?

I investigated this a bit and i see that the sizeHint method of HTMLDelegate is sometimes called with an options parameter which contains a rectangle with attributes (0, 0, 0, 0). And the display behaviour finally changes after the call of doc.setTextWidth(options.rect.width()). But i couldnt finally find out who calls it with this parameter and how i could properly fix this.

Can somebody explain where this comes from and how i can fix this porperly?

Why are queries faster when subqueries within the WITH clause are duplicated?

Suppose a project uses partitions to structure its data. This concept is purely business specific and does not have to do with database partitioning.

Let's say the business logic does:

  • delete from output_table where partition = < partitionX >
  • insert into output_table (select * from input_table where partition = < partitionX >)

Keeping in mind that everything is structured like that, let's complicate a problem (to get to the actual question).

Suppose that I have a query (the SELECT query) that is potential killer, in terms of time :

insert into output_table (
  select * 
   from input_table
   left outer join additional_table additional_table1  
     on input_table.id = additional_table1.id
   left outer join additional_table additional_table2  
    on additional_table2.id = additional_table1.parent
  where partition =  <partitionX>
)

Let's optimize this and explore the options. Keep in mind every table has partitions. Also notice how table2 is joined twice, but on different columns. And, also notice how the additional table is joined on itself

Everything uses the WITH clause, but there are several options and I would like to know why one of these is better.

A. direct and duplicate queries in the WITH section

WITH 
CACHED_input_table AS (
  SELECT *
  FROM input_table
  WHERE PARTITION_ID = < partition  X >
),
CACHED_additional_table1 AS (
  SELECT *
  FROM additional_table 
  WHERE PARTITION_ID = < partition  X >
),
CACHED_additional_table2 AS (
  SELECT *
  FROM additional_table 
  WHERE PARTITION_ID = < partition  X >
)
SELECT *    
FROM CACHED_input_table input_table
  LEFT OUTER JOIN CACHED_additional_table1 additional_table1 
    ON input_table.ID = additional_table1.ID
  LEFT OUTER JOIN CACHED_additional_table2 additional_table2 
    ON additional_table1.PARENT_ID = additional_table2.ID

B. reuse of query in the FROM section

WITH 
CACHED_input_table AS (
  SELECT *
  FROM input_table
  WHERE PARTITION_ID = < partition  X >
),
CACHED_additional_table AS (
  SELECT *
  FROM additional_table 
  WHERE PARTITION_ID = < partition  X >
)
SELECT *    
FROM CACHED_input_table input_table
  LEFT OUTER JOIN CACHED_additional_table additional_table1 
    ON input_table.ID = additional_table1.ID
  LEFT OUTER JOIN CACHED_additional_table additional_table2 
    ON additional_table1.PARENT_ID = additional_table2.ID

C. reuse of query in the WITH section

WITH 
CACHED_input_table AS (
  SELECT *
  FROM input_table
  WHERE PARTITION_ID = < partition  X >
),
CACHED_additional_table1 AS (
  SELECT *
  FROM additional_table 
  WHERE PARTITION_ID = < partition  X >
),
CACHED_additional_table2 AS (
  SELECT *
  FROM CACHED_additional_table1 
)
SELECT *    
FROM CACHED_input_table input_table

LEFT OUTER JOIN CACHED_additional_table1 additional_table1 
 ON input_table.ID = additional_table1.ID

LEFT OUTER JOIN CACHED_additional_table2 additional_table2 
 ON additional_table1.PARENT_ID = additional_table2.ID

From experience, Option A is the fastest. But why? Can someone explain this? (I am playing on Oracle v11.2)

I know that, potentially, my optimization around this company specific concept of partitions has nothing to do with the generic sql optimization around WITH clause that I am asking about, but please take it as a real-life example.

Explain plans

Option A (9900 rows in 7s)

------------------------------------------------------------------------------------------------------------------------
| Id  | Operation               | Name                         | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT        |                              |     1 |  1037 | 18540   (8)| 00:00:03 |       |       |
|*  1 |  HASH JOIN OUTER        |                              |     1 |  1037 | 18540   (8)| 00:00:03 |       |       |
|*  2 |   HASH JOIN OUTER       |                              |     1 |   605 |  9271   (8)| 00:00:02 |       |       |
|   3 |    PARTITION LIST SINGLE|                              |     1 |   173 |     2   (0)| 00:00:01 |   KEY |   KEY |
|   4 |     TABLE ACCESS FULL   | input_table                  |     1 |   173 |     2   (0)| 00:00:01 |    24 |    24 |
|   5 |    PARTITION LIST SINGLE|                              |  1362K|   561M|  9248   (8)| 00:00:02 |   KEY |   KEY |
|   6 |     TABLE ACCESS FULL   | additional_table             |  1362K|   561M|  9248   (8)| 00:00:02 |    24 |    24 |
|   7 |   PARTITION LIST SINGLE |                              |  1362K|   561M|  9248   (8)| 00:00:02 |   KEY |   KEY |
|   8 |    TABLE ACCESS FULL    | additional_table             |  1362K|   561M|  9248   (8)| 00:00:02 |    24 |    24 |
------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("additional_table"."PARENT"="additional_table"."ID"(+))
   2 - access("input_table"."ID"="additional_table"."ID"(+))

Option B (9900 rows in 10s)

---------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                  | Name                         | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
---------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |                              |     1 |  2813 | 18186  (11)| 00:00:03 |       |       |
|   1 |  TEMP TABLE TRANSFORMATION |                              |       |       |            |          |       |       |
|   2 |   LOAD AS SELECT           | SYS_TEMP_0FD9D6CA2_C26AF925  |       |       |            |          |       |       |
|   3 |    PARTITION LIST SINGLE   |                              |  1362K|   561M|  9248   (8)| 00:00:02 |   KEY |   KEY |
|   4 |     TABLE ACCESS FULL      | additional_table1            |  1362K|   561M|  9248   (8)| 00:00:02 |    24 |    24 |
|*  5 |   HASH JOIN OUTER          |                              |     1 |  2813 |  8939  (15)| 00:00:02 |       |       |
|*  6 |    HASH JOIN OUTER         |                              |     1 |  1493 |  4470  (15)| 00:00:01 |       |       |
|   7 |     PARTITION LIST SINGLE  |                              |     1 |   173 |     2   (0)| 00:00:01 |   KEY |   KEY |
|   8 |      TABLE ACCESS FULL     | input_table                  |     1 |   173 |     2   (0)| 00:00:01 |    24 |    24 |
|   9 |     VIEW                   |                              |  1362K|  1714M|  4447  (14)| 00:00:01 |       |       |
|  10 |      TABLE ACCESS FULL     | SYS_TEMP_0FD9D6CA2_C26AF925  |  1362K|   561M|  4447  (14)| 00:00:01 |       |       |
|  11 |    VIEW                    |                              |  1362K|  1714M|  4447  (14)| 00:00:01 |       |       |
|  12 |     TABLE ACCESS FULL      | SYS_TEMP_0FD9D6CA2_C26AF925  |  1362K|   561M|  4447  (14)| 00:00:01 |       |       |
---------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   5 - access("additional_table1"."PARENT"="additional_table2"."ID"(+))
   6 - access("input_table"."ID"="additional_table1"."ID"(+))

Option C (9900 rows in 17s)

---------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                  | Name                         | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
---------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |                              |     1 |  2813 | 18186  (11)| 00:00:03 |       |       |
|   1 |  TEMP TABLE TRANSFORMATION |                              |       |       |            |          |       |       |
|   2 |   LOAD AS SELECT           | SYS_TEMP_0FD9D6CA7_C26AF925  |       |       |            |          |       |       |
|   3 |    PARTITION LIST SINGLE   |                              |  1362K|   561M|  9248   (8)| 00:00:02 |   KEY |   KEY |
|   4 |     TABLE ACCESS FULL      | additional_table             |  1362K|   561M|  9248   (8)| 00:00:02 |    24 |    24 |
|*  5 |   HASH JOIN OUTER          |                              |     1 |  2813 |  8939  (15)| 00:00:02 |       |       |
|*  6 |    HASH JOIN OUTER         |                              |     1 |  1493 |  4470  (15)| 00:00:01 |       |       |
|   7 |     PARTITION LIST SINGLE  |                              |     1 |   173 |     2   (0)| 00:00:01 |   KEY |   KEY |
|   8 |      TABLE ACCESS FULL     | input_table                  |     1 |   173 |     2   (0)| 00:00:01 |    24 |    24 |
|   9 |     VIEW                   |                              |  1362K|  1714M|  4447  (14)| 00:00:01 |       |       |
|  10 |      TABLE ACCESS FULL     | SYS_TEMP_0FD9D6CA7_C26AF925  |  1362K|   561M|  4447  (14)| 00:00:01 |       |       |
|  11 |    VIEW                    |                              |  1362K|  1714M|  4447  (14)| 00:00:01 |       |       |
|  12 |     TABLE ACCESS FULL      | SYS_TEMP_0FD9D6CA7_C26AF925  |  1362K|   561M|  4447  (14)| 00:00:01 |       |       |
---------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   5 - access("additional_table1"."PARENT_ID"="CACHED_additional_table"."ID"(+))
   6 - access("input_table"."ID"="additional_table1"."ID"(+))

EDIT :

  • added explain plans
  • edited base query : there is an input_table, and an additional_table that is joined twice, once on input_table, and once on itself
  • edited query for option A : there is an input_table, and the additional_table is joined twice, once on input_table, and once on a duplicate of itself (additional_table)
  • edited query for Option B : there is an input_table, and the additional_table is joined twice, once on input_table, and once on itself, using the same alias(additional_table)
  • edited query for Option C : there is an input_table, and the additional_table is joined twice, once on input_table, and once on another table created from itself in the WITH section