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.