dimanche 31 mai 2015

Interceptor Method Not Invoked

The container is Glassfish. I have implemented an @PostConstruct life-cycle event interceptor method in a simple DAO bean class, but seems like for some reason it is not intercepting my business method at all. I do not anywhere manually instantiate the bean classes.

public class DefaultUserDao implements UserDao {

    private String userName;
    private String password;
    Scanner users = null;
    String[] userNamePasswordPairs = null;

    public DefaultUserDao() {
        try {
            users = new Scanner(Paths.get("/home/nhuyvan1106/NetBeansProjects/EJBInAction/web/users"));
        } 

        catch (IOException ex) {
            Logger.getLogger(DefaultUserDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /*The interceptor for this method is defined right below, that 
      interceptor method is not called at all. If I insert a
      System.out.println(userNamePasswordPairs) after the split()
      method below, it prints [userName:password] pair twice and there
      is only one line in the text file from which the pair was read  in the
      form like this admin:admin. Notice that I also insert a System.out.println()
      method in the interceptor method but if I remove the print()
      method from this init() method, I don't see it prints anything
      */
    @PostConstruct
    public void init() {
        while (users.hasNextLine()) {
            String line = users.nextLine();
            userNamePasswordPairs = line.split(":");
            //If I uncomment this, I see it prints [admin:admin] pair
            //twice, but when I comment it out, I don't see it prints  anything
           //System.out.println(Arrays.toString(userNamePasswordPairs));
            userName = userNamePasswordPairs[0];
            password = userNamePasswordPairs[1];
        }
    }

    @AroundConstruct
    private void printUser(InvocationContext ic) {
        System.out.println("Interceptor invoked: " + Arrays.toString(userNamePasswordPairs));
        try {
            ic.proceed();
        } 

        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

A simple JSF page gathering username and password

@Named
@RequestScoped
public class LoginBean {

    private String userName;
    private String password;

    @Inject
    private UserDao userDao;

    public LoginBean() {
    }

    public LoginBean(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    public String validateUser() {

        if (userDao.getUserName().equals(userName) && userDao.getPassword().equals(password)) {
        }

        else {
            userName = "Error";
            password = "Error";
        }
        return "confirmation.xhtml";
    }

    //getter and setter for userName and password

}

redirect user to login page

I'm running a J2EE application and need to redirect the user to login page if the session is inactive.

I basically want to use the below javascript code to get the session last accessed time and compare with the current time, and if its more than the session timeout I will logout:-

<script>

        setInterval(function() {

            console.log('MaxInactive Interval ==  ' + <%=new Date(session.getLastAccessedTime())%> );

        }, 10000);
    </script>

I get the below error on the console.log line:-

Uncaught SyntaxError: missing ) after argument list

Here is the display from the sources tab:-

console.log('MaxInactive Interval ==  ' + Sun May 31 20:33:17 EDT 2015 );

Create build.xml file independant of the location of the libraries

In order to generate a war file , I've created a build.xml file via eclipse. The build.xml is as shown below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
              Any modifications will be overwritten.
              To include a user specific buildfile here, simply create one in the same
              directory with the processing instruction <?eclipse.ant.import?>
              as the first entry and export the buildfile again. --><project basedir="." default="build" name="project">
    <property environment="env"/>
    <property name="ECLIPSE_HOME" value="../../../Documents/Eclipse EE/eclipse/"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.6"/>
    <property name="source" value="1.6"/>
    <path id="WebLogic System Libraries.libraryclasspath">
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.persistence_1.1.0.0_2-0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.oracle.jpa2support_1.0.0.0_2-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/wlserver_10.3/server/lib/api.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/glassfish.jstl_1.2.0.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.jsf_1.1.0.0_1-2.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.ejb_3.0.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.enterprise.deploy_1.2.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.interceptor_1.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.jms_1.1.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.jsp_1.3.0.0_2-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.jws_2.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.activation_1.1.0.0_1-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.mail_1.1.0.0_1-4-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.xml.soap_1.3.1.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.xml.rpc_1.2.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.xml.ws_2.1.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.management.j2ee_1.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.resource_1.5.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.servlet_1.0.0.0_2-5.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.transaction_1.0.0.0_1-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.xml.stream_1.1.1.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.security.jacc_1.0.0.0_1-1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/javax.xml.registry_1.0.0.0_1-0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/wlserver_10.3/server/lib/wls-api.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.apache_1.3.0.1.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.i18n_1.9.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.logging_1.9.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.utils.full_1.10.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.utils.wrapper_1.4.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.utils.classloaders_2.0.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.common.security.providers.env_1.0.0.0_6-2-0-0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.common.security.saml2.manage_1.0.0.0_6-2-0-0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.weblogic.web.api_1.4.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.weblogic.rmi.client_1.11.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.transaction_2.7.1.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.workarea_1.8.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.xml.weblogic.xpath_1.5.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.datasource6_1.10.0.0.jar"/>
        <pathelement location="../../../../../Oracle/Middleware/modules/com.bea.core.weblogic.stax_1.10.0.0.jar"/>
    </path>
    <path id="Web App Libraries.libraryclasspath">
        <pathelement location="WebContent/WEB-INF/lib/log4j-1.2.17.jar"/>
    </path>
    <path id="EAR Libraries.libraryclasspath"/>
    <path id="project.classpath">
        <pathelement location="boum/classes"/>
        <path refid="WebLogic System Libraries.libraryclasspath"/>
        <path refid="Web App Libraries.libraryclasspath"/>
        <path refid="EAR Libraries.libraryclasspath"/>
    </path>
    <path id="run.Test.bootclasspath">
        <fileset dir="${java.home}/lib" includes="*.jar"/>
        <fileset dir="${java.home}/lib/ext" includes="*.jar"/>
        <path refid="WebLogic System Libraries.libraryclasspath"/>
    </path>
    <target name="init">
        <mkdir dir="boum/classes"/>
        <copy includeemptydirs="false" todir="boum/classes">
            <fileset dir="client">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
        <copy includeemptydirs="false" todir="boum/classes">
            <fileset dir="test">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
        <copy includeemptydirs="false" todir="boum/classes">
            <fileset dir="src">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>
    <target name="clean">
        <delete dir="boum/classes"/>
    </target>
    <target depends="clean" name="cleanall"/>
    <target depends="build-subprojects,build-project" name="build"/>
    <target name="build-subprojects"/>
    <target depends="init" name="build-project">
        <echo message="${ant.project.name}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="boum/classes" includeantruntime="false" source="${source}" target="${target}">
            <src path="client"/>
            <src path="test"/>
            <src path="src"/>
            <classpath refid="project.classpath"/>
        </javac>
    </target>
    <target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/>
    <target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
        <copy todir="${ant.library.dir}">
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </copy>
        <unzip dest="${ant.library.dir}">
            <patternset includes="jdtCompilerAdapter.jar"/>
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </unzip>
    </target>
    <target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
        <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
        <antcall target="build"/>
    </target>
    <target name="Test">
        <java classname="Test" failonerror="true" fork="yes">
            <classpath refid="project.classpath"/>
            <bootclasspath>
                <path refid="run.Test.bootclasspath"/>
            </bootclasspath>
        </java>
</target>
 <target name="war" description="Bundles the application as a WAR file" depends="clean, build">
            <mkdir dir="WebContent/WEB-INF/classes"/>
            <copy includeemptydirs="false" todir="WebContent/WEB-INF/classes">
                    <fileset dir="boum/classes">
                    <include name="**/**"/>
                    </fileset>
            </copy>
             
            <war destfile="boumboum.war"
                basedir="WebContent"
                needxmlfile="false">
            </war>
        </target>
</project>

So my question is: how can I write this build.xml file in a way that is independant from the location of the libraries which is my computer ? Let's say I run this build file in a computer which doesn't contains the folders Oracle/Middleware. In that case I guess it wont generate the war file. Is there a way to make it work ? If so ,could you show me an example or point me to some tutorials where they do it. Because i'm completely new with ant.

Oops: PersistenceException. How to properly configure Play 1.3?

When I working with my application I often get the following exception:

Oops: PersistenceException An unexpected error occured caused by exception PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection

This exception has been logged with id 6mb2ocokg

... 6 more Caused by: java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
        at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
        at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:77)
        at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141)
        at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:301)
        at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
        ... 11 more Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@42623a9d -- timeout at awaitAvailable()
        at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1461)
        at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:639)
        at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:549)
        ... 14 more

Just a few requests and my application stop working... I want to ask how to properly configure Play application?

Maybe I need to use DTO pattern before rendering? I'm asked about it here -

Do I need to use DTO in Play Framework before data rendering?

My application.conf (relevant part):

# This is the main configuration file for the application.
# ~~~~~


# Application mode
# ~~~~~
# Set to dev to enable instant reloading and other development help.
# Otherwise set to prod.
application.mode=dev
%prod.application.mode=prod

# Server configuration
# ~~~~~
# If you need to change the HTTP port, uncomment this (default is set to 9000)
# http.port=9000

http.port=80


# Session configuration
# ~~~~~~~~~~~~~~~~~~~~~~
# By default, session will be written to the transient PLAY_SESSION cookie.
# The cookies are not secured by default, only set it to true
# if you're serving your pages through https.
# application.session.cookie=PLAY
# application.session.maxAge=1h
# application.session.secure=false


# JVM configuration
# ~~~~~
# Define which port is used by JPDA when application is in debug mode (default is set to 8000)
# jpda.port=8000
jpda.port=8080
#
# Java source level => 1.6, 1.7 or 1.8 (experimental)
# java.source=1.6


# Database configuration
# ~~~~~ 
# Enable a database engine if needed.
#
# To quickly set up a development database, use either:
#   - mem : for a transient in memory database (H2 in memory)
#   - fs  : for a simple file written database (H2 file stored)
# db.default=mem
#
# To connect to a local MySQL5 database, use:
# db.default=mysql://user:pwd@host/database
#
# To connect to a local PostgreSQL9 database, use:
# db=postgres://user:pwd@host/database
#
# If you need a full JDBC configuration use the following :
# db.default.url=jdbc:postgresql:database_name
# db.default.driver=org.postgresql.Driver
# db.default.user=root
# db.default.pass=secret
#
# Connections pool configuration :
# db.default.pool.timeout=1000
# db.default.pool.maxSize=30
# db.default.pool.minSize=10
#
# If you want to reuse an existing Datasource from your application server, use:
# db.default=java:/comp/env/jdbc/myDatasource
#
# When using an existing Datasource, it's sometimes needed to destroy it when
# the application is stopped. Depending on the datasource, you can define a
# generic "destroy" method :
# db.default.destroyMethod=close


########### db.default.logStatements=true
########### logger.org.hibernate=DEBUG


# JPA Configuration (Hibernate)
# ~~~~~
#
# Specify the custom JPA dialect to use here (default to guess):
# jpa.default.dialect=org.hibernate.dialect.PostgreSQLDialect
#
# Specify the ddl generation pattern to use. Set to none to disable it 
# (default to update in DEV mode, and none in PROD mode):
# jpa.default.ddl=update
#
# Debug SQL statements (logged using DEBUG level):
# jpa.default.debugSQL=true
#
# You can even specify additional hibernate properties here:
# default.hibernate.use_sql_comments=true
# ...
#
# Store path for Blob content
attachments.path=data/attachments

# Memcached configuration
# ~~~~~ 
# Enable memcached if needed. Otherwise a local cache is used.
# memcached=enabled
#
# Specify memcached host (default to 127.0.0.1:11211)
# memcached.host=127.0.0.1:11211
#
# Or you can specify multiple host to build a distributed cache
# memcached.1.host=127.0.0.1:11211
# memcached.2.host=127.0.0.1:11212
#
# Use plain SASL to authenticate for memcached
# memcached.user=
# memcached.password=


# Execution pool
# ~~~~~
# Default to 1 thread in DEV mode or (nb processors + 1) threads in PROD mode.
# Try to keep a low as possible. 1 thread will serialize all requests (very useful for debugging purpose)
# play.pool=3

jpa.debugSQL=true
jpa.meteo.debugSQL=true
jpa.ddl=none

#~~~~~~~~~~ SQL Server JTDS config ~~~~~~~~~

jpa.dialect=org.hibernate.dialect.SQLServerDialect
db.default.url=jdbc:jtds:http://sqlserverip2_here/sid3_here
db.default.driver=net.sourceforge.jtds.jdbc.Driver
db.default.user=...
db.default.pass=...
db.default.dialect=org.hibernate.dialect.SQLServerDialect
db.default.pool.timeout=30000
db.default.pool.maxSize=300
db.default.pool.minSize=100

db.info.dialect=org.hibernate.dialect.SQLServerDialect
db.info.url=jdbc:jtds:http://sqlserverip2_here/sid2_here
db.info.driver=net.sourceforge.jtds.jdbc.Driver
db.info.user=...
db.info.pass=...
db.info.pool.timeout=30000
db.info.pool.maxSize=300
db.info.pool.minSize=100
jpa.info.dialect=org.hibernate.dialect.SQLServerDialect

db.meteo.dialect=org.hibernate.dialect.SQLServerDialect
db.meteo.url=jdbc:jtds:http://sqlserverip1_here/sid1_here
db.meteo.driver=net.sourceforge.jtds.jdbc.Driver
db.meteo.user=...
db.meteo.pass=...
db.meteo.pool.timeout=30000
db.meteo.pool.maxSize=300
db.meteo.pool.minSize=100
jpa.meteo.dialect=org.hibernate.dialect.SQLServerDialect

play.pool=3
hibernate.temp.use_jdbc_metadata_defaults=false
module.secure=${play.path}/modules/secure

I would be very grateful for the information. Thanks to all.

how can i load data insinde tag div using ZK

I want to see progress increase in progressbar, i already use progressmeter of ZK. but now i'm using an other progressbar in div like that <div if="${item.progres ge '35'}" class="progress-bar progress-bar-success"> <span class="sr-only"></span></div></div>

How to run project with Tomcat running on digital ocean

I have started to learn about J2EE and have started to install Tomcat onto my digital ocean from using the following Tutorial: http://ift.tt/1spRl6E

BUT, when i run the application to the desired location it directs me to the welcome page. How do i go about making it run to my project application?

I read something about WAR file but cannot see it on my Intelliji same goes with POM.XML

I have already configured the Tomcat configuration to Tomcat Server remote with host as the IP and default port of 8080.

Everytime i deploy application to the following URL: http://IP.Address:8080/ it returns a welcome page as shown from below URL of the screenshot.

http://ift.tt/1GdXTAD

jQuery Data Table server side processing with Java

I am looking for how to implement jQuery Data Table with server side processing in Java. I have tried the following way by using the below parameters. Below is my jQuery ready function code.

$(document).ready(function() {
    //url = http://localhost:8080/jQuery-DataTable-Java-Integration/serverExample
    $('#myTableId').DataTable({
        "serverSide" : true,
        "processing" : true,
        /*"bProcessing" : true,
        "bServerSide" : true,*/
        "ajax" : {
            "url" : "serverExample",
            "type" : "POST"
        },
        "columns" : [ {
            "data" : "Phone Number"
        }, {
            "data" : "name"
        }, {
            "data" : "Email"
        } ]
    });
});

In my servlet doPost() method I the request parameter sEcho is null.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("In do post method of server servlet..");
        logger.info("sEcho request parameter = " + request.getParameter("sEcho"));//returning null
//other code here
}

My jQuery Data Table version is 1.10.7. Which parameters should be used, serverSide or bServerside, I tried both ways, but still the same. Any latest updated working example references would be helpful.

two entities having relationship but they are not in the same ejb

I have entity A in ejb a and entity B in ejb b and one ear project wich contains the two ejb plus one app swing client.

@entity
public class A{                 
    //attributes
    @oneToOne
    B b;
 }
 @entity
 public class B{                 
    //attributes 
 }

I want to know how to do this if they are not in the same ejb.
Thanks for you all

Handling servlets exceptions

I am getting troubles with handling exceptions in web servlet app. I've created ErrorHandler servlet, which handles all incoming exceptions and added entry in web.xml file :

<servlet>
    <servlet-name>ErrorHandler</servlet-name>
    <servlet-class>ServletPackage.ErrorHandler</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ErrorHandler</servlet-name>
    <url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/ErrorHandler</location>
</error-page>

The problem is the server does not invoke ErrorHandler servlet at all. Glassfish just throws Exception in the console and web browser refreshes the servlet which thrown exception (with no data due to unhandled exception).

Warning:   StandardWrapperValve[SessionChecker]: Servlet.service() for servlet SessionChecker threw exception
javax.servlet.ServletException: Forced exception thrown
    at ServletPackage.SessionChecker.processRequest(SessionChecker.java:158)
    at ServletPackage.SessionChecker.doPost(SessionChecker.java:174)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
   .
   .
   .

Any suggestions?

Alternative of JTATransaction

I have an Spring based J2EE application which runs well on Weblogic, I wanted to move it to Tomcat.

It seems tomcat doesn't support JTA Transaction Manager without external jar help like Atomikos, JOTM, Bitronix, SimpleJTA.

I am reluctant to make changes into my application where i am already using annotation based JTA transaction manager.

Are there alternatives for JTA Transaction Manager which I can use so that I am able to switch from weblogic to tomcat or tomcat to weblogic or any other server without changing my configuration file each time?

All in all what's best for transaction manager configuration when you want to keep your application (war) independent of server(s).

samedi 30 mai 2015

Run Oracel tuturial's examples of java ee in Netbeans

I want to run a simple example of j2ee Hello in Netbeans.

Based on the Orcale tutorials, i must open File menu, choose Open Project. Then In the Open Project dialog, navigate to:

tut-install/examples/web/

but the problem is, I can not find such this root in my computer

please give me a hint?

Create table programatically from entity annotation under JPA

Suppose the JPA provider is hibernate. Suppose it is not container managed, but application managed.

Given an entity class and correct annotation, is it possible to create table programatically, at runtime, and only for that class? By saying runtime, it means the entity class is not listed in the persistence.xml.

Theoretically, it is possible because we can manually read the annotations and generate SQL, and from the persistence unit we can read database connection url. My question is, is there anyway to do it without duplicating lots of work inside hibernate?

I found in other SO questions that Persistence.createSchema could be used, but I don't see where to specify the class.

Single instance of PicketLink for multiple applications

My intention is to implement with PicketLink something similar to what Atlassian has done in Crowd.

In more detail, I want single PicketLink instance to provide authentication, authorization, SSO and IdM services to multiple Java EE applications. The point here is to have a single place for JPA/LDAP configuration, custom IdM model and custom authenticators (all the above will be shared between client applications).

As far as I've learned from the documentation, PicketLink doesn't offer this out of the box. I would imagine client applications using PicketLink APIs, but the actual calls being proxied to master PicketLink instance via RMI/Hessian/REST etc. I would appreciate any expert opinion on whether this architecture will be viable, as well as any other criticisms and suggestions.

Criteria API and Entity Graph

I have two entities with unidirectional lazy relations. And one of them has a named entity graph. Here are the entities (getters and setter are not listed due to readability):

    @Entity
    @NamedEntityGraph (
            name = "Sms.fetchSims",
            attributeNodes = {
                    @NamedAttributeNode("sim")
            }
    )
    public class Sms {
        @Id
        @GeneratedValue (strategy = GenerationType.AUTO)
        private Long id;
        @NotNull
        private Timestamp date;
        @NotNull
        private String sender;
        @NotNull
        private String content;

        @NotNull
        private Direction direction;

        @NotNull
        @ManyToOne (fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
        private Sim sim;
    }

    @Entity
    public class Sim {
        @Id
        @GeneratedValue (strategy = GenerationType.AUTO)
        private long id;

        @NotNull
        private long IMSI;

        private String MSISDN;
        private String provider;
        private Timestamp lockedDate;
    }

When I fetch any sms using the entity manager find() method with this entity graph, I get an sms with a sim. But i want to be able to find smses by sim id. That's why i created a criteria api query for that purpose.

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    EntityGraph eg = entityManager.getEntityGraph("Sms.fetchSims");

    CriteriaQuery<Sms> cq = cb.createQuery(Sms.class);
    Root<Sms> smses = cq.from(Sms.class);
    Join<Sms, Sim> sims = smses.join(Sms_.sim);
    cq.where(cb.equal(sims.get(Sim_.id), simId));
    cq.orderBy(cb.desc(smses.get(Sms_.date)));

    return entityManager
        .createQuery(cq)
        .setHint("javax.persistence.fetchgraph", eg)
        .setMaxResults(1000)
        .getResultList();

As you see, i set the entity graph here using a setHint method of the typed query, but sim is never fetched, it's fields are not even listed in the result sql. What could i do to make entity graph work with criteria api?

I know I can typecast smses.fetch(Sms_.sim) to Join, but i get ugly warnings, and this method looks like a dirty hack to me.

I'm working with hibernate and wildfly-8.2.0.Final application server.

JPA (hibernate) does not insert on persist, needs to be flushed

I have a stateless bean that observes an event and save a record:

@Stateless
public class Manager {
    @Inject
    Repository repository;

    Manager() {}

    @Inject
    Manager(Repository repository) {
        this.repository = repository;
    }

    public void EventHandler(@Observes MyEvent myEvent) {
        save(event.obj);
    }

    private save(Object object) {
        repository.add(object);
    }
}

My repository is like this:

@Stateless
public class Repository {
    @PersistenceContext
    EntityManager em;

    Repository() {}

    public void add(Object object) {
        em.persist(object);
        // em.flush();  <---
    }
}

It doesn’t work unless I uncomment the line The thing I don’t understand is why do I need to flush! Shouldn’t the transaction commit automatically?

what annotation to create a web service that is created only once when the server starts?

I am stuck on what annotation to use to create a web service where only one instance is created when the server starts I have written a service which contains a time stamp which should be the same time each refresh of the page but the time changes with each local refresh

This is the code I've got

@Path("/message")
@Startup
@Singleton
public class TestEndPoint
{
@Inject ConfigurationService configurationService;
@GET

@Path("/test")
@Produces("application/json")

public String printMessage()
{
    //ConfigurationService configurationService = new
    ConfigurationService();
    return configurationService.getPropertiesJSONString();
}
}

public class ConfigurationService
{
@Inject Configuration configuration;
private String propertiesJSONString;

public String getPropertiesJSONString()
{
    try
    {
        Properties properties = configuration.getProperties();
        ObjectMapper objectMapper = new ObjectMapper();
        propertiesJSONString = objectMapper.writeValueAsString(properties);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return propertiesJSONString;
}

public void setPropertiesJSONString(String propertiesJSONString)
{
    this.propertiesJSONString = propertiesJSONString;
}

public ConfigurationService()
{

}
}

public class Configuration implements Serializable
{

private Properties properties;

public Configuration()
{
    // TODO Auto-generated constructor stub
}

public Properties getProperties() throws IOException
{

    Properties prop = new Properties();
    String propFileName = System.getProperty("propertiesfilelocation");
    InputStream inputStream = null;

    inputStream = new FileInputStream(propFileName);

    if (inputStream != null)
    {
        prop.load(inputStream);
    }
    else
    {

    }

    Date date = new Date();
    SimpleDateFormat formatter = 
    new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
    String formattedDate = formatter.format(date);
    prop.put("time", formattedDate);

    return prop;
}

public void setProperties(Properties properties)
{
    this.properties = properties;
}

}

and it works apart from the time that is returned with each JSON string is updated with each local refresh, I want to know the annotation required so that it will be the same each time the page is visited

Is GlassFish Server having any relation with Java EE SDK

As for obtaining Glassfish server we have download Java EE SDk. Is there any co-relation of GlassFish server and Java EE SDK. Did we need to download the same for JBoss and Apache Tomcat

registering custom maven archetype

How can I register my own Maven archetype, co that other people (in the whole world or just in my local company) might use it?

In Python, there is PyPI, a global registry where you create packages, upload them, upgrade, ... and you've got a user there which you use to authorize your self.

In node.js, there is npm, which works exactly the same. There is also bower, which is similar (though it relies on git branches).

Anyway, this tutorial describes that I can install an archetype locally. But how can I make it public, so that other people may download it? How is it integrated with IDEs (Eclipse, NetBeans, etc.)?

GlassFish Server as Java EE software development kit (SDK)

Why we called GlassFish Server as Java EE software development kit (SDK). Then what should we don't called Apache Tomcat, Jboss and many other as Java EE software development kit. As Glassfish is also an server and used for deployment purpose so we can call it as a SDK. I am really confused with this concept of Java EE 7 SDk.

sitemesh with spring MVC with annotation @Configuration (without web.xml file)

I want to use SiteMesh with spring MVC using annotations I already work with but using web.xml this is my config javaclass

    @EnableWebMvc
    @Configuration
    @ComponentScan({ "ma.boubia.x.*" })
    @EnableTransactionManagement
    @Import({ SecurityConfig.class })
    public class AppConfig {

/* 
BEANS Declarations
*/
    }

thank you

what is the best way to print invoice in java

in my desktop application (POS System). I used IText api for generating invoices and printing, but my printer thermal invoice printer don't support .pdf file. only supporting text file and .docx file. i use simple text file printer print whole invoice in long vertical single word line and don't auto cut page. I used .docx file which works good, i got print as i designed. but my program first open document in ms word then give me print. my code is:

try

     {


            FileOutputStream output = new FileOutputStream(FILE);                   
                    XWPFDocument doc = new XWPFDocument();

                    CTBody body = doc.getDocument().getBody();
                    if(!body.isSetSectPr()){
                    body.addNewSectPr();
                    }

                    CTSectPr section = body.getSectPr();
                    if(!section.isSetPgSz()){
                    section.addNewPgSz();
                    }
                    CTPageSz pageSize = section.getPgSz();
                    pageSize.setOrient(STPageOrientation.PORTRAIT);

                    int value = 4000+(gui.model.getRowCount()*1000);

                    pageSize.setW(BigInteger.valueOf(4050));
                    pageSize.setH(BigInteger.valueOf(value));

                    CTPageMar pageMar = section.addNewPgMar();
                    pageMar.setLeft(BigInteger.valueOf(400L));
                    pageMar.setTop(BigInteger.valueOf(0L));
                    pageMar.setRight(BigInteger.valueOf(0L));
                    pageMar.setBottom(BigInteger.valueOf(0L));

                     XWPFParagraph para = doc.createParagraph();
                     para.setAlignment(ParagraphAlignment.LEFT);
                     XWPFRun run  = para.createRun();
                     para.setWordWrap(true);
                     run.setBold(true);
                     run.setFontSize(10);
                     run.setText("          "+address.shopName);
                     run.addBreak();
                     run.setText("                        "+address.phoneNo);
                     run.addBreak();
                     run.setText("   "+address.description);
                     run.addBreak();
                     para = doc.createParagraph();
                    para.setAlignment(ParagraphAlignment.LEFT);
                    run  = para.createRun();
                     para.setWordWrap(true);
                     run.setFontSize(10);
                     run.setText("Invoice No."+invoiceno);
                     run.addBreak();
                     run.setText("Type: "+table);
                     run.addBreak();
                     run.setText("Customer Name: "+name+"    "+tempObj);
                     run.addBreak();
                     run.setText("--------------------------------------------------------");
                     run.addBreak();
                     run.setText("Product              Qty          Price          Total");
                     run.addBreak();
                     run.setText("--------------------------------------------------------");
                     run.addBreak();

                String temp = null;
                for(int i = 0 ; i < gui.table.getRowCount(); i++){
                    temp = gui.table.getValueAt(i, 1).toString();
                    String quanstr = gui.table.getValueAt(i, 2)+"";
                    String unitPricestr = gui.table.getValueAt(i, 3)+"";
                    String totalstr =gui.table.getValueAt(i, 4)+"";

                    run.setText(temp);run.addBreak();
                     run.setText("                            "+quanstr+"          "+unitPricestr+"          "+totalstr);
                     run.addBreak();
                }
                double subTotal = tableTotalCounter();
                run.setText("--------------------------------------------------------");run.addBreak();
                run.setText("Discount: "+dis+"%");run.addBreak();
                run.setText("Sub total: "+(subTotal - (subTotal*dis/100)));run.addBreak();
                run.setText("Cash: "+cash);run.addBreak();
                run.setText("Balance: "+(cash-(subTotal - (subTotal*dis/100))));
                run.addBreak();
                doc.write(output); 
                output.close();

                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    System.out.println("Exception");
                    e1.printStackTrace();
                }catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("Exception");
                }

            if(confirmation("Print invoice?","Confirmation")==0){
                Desktop desktop = Desktop.getDesktop();
                try {

                     desktop.print(new File(FILE));
                } catch (IOException e) {           
                    e.printStackTrace();
                }
      }

please tell me how to print without getting that file open. and there is any other way to print invoice.

What framework is the best option for creating a gaming website?

I am starting a gaming website which will require exchanging data between a gamer and the gaming server on regular basis. Since i am new to Java and i have worked with a bit of Java Beans, i would like to know that based on my requirements, which framework would be a good one among the following:

  • EJB
  • Spring
  • Struts

I know that it is possible to do this with every framework, but of course certain frameworks are more preferred in some cases.

Since i am new to these technologies, i am therefore not sure which one to follow for creating the gaming website. Any help would be appreciated.

Printing word documents without reviewing and starting MSWord

My software generates .docx file for the invoice. but my software stops responding when i click on print invoice. because system start waiting for starting ms-word and review document. my my system could not handle due to low speed.i am using following code to print.

String FILE = helper+"InvoiceCode"+invoiceno+".docx";
    Desktop desktop = Desktop.getDesktop();
                    try {
                         desktop.print(new File(FILE));
                    } catch (IOException e) {          
                    }

i want to print immediatly without review and starting MS-Word. pleas try to help urgently. I will be thankfull

what is a significance of "Java 2" in J2EE?

Why J2EE why not J7EE or J8EE . We got latest version as Java 8. But, why still, it is being Java Platform 2 ? What is a significance of "2" here ? Or It looks good, that's why they never changed its name or some other reason ?

Creating jpa entities of several types

My project has 3 types of users. One type has all attributes of the other two types. I have a entity call User. And I extended UserType1 and UserType2 from User. And I want all properties of Type1 and Type2 to be there in Type3. How can I do it in JPA entities.

vendredi 29 mai 2015

File-upload with multiple files fails in Primefaces 5.1

I try to do a file upload in primefaces with PF 5.1 and OmniFaces version 1.7.

My .xhtml code:

<h:form id="fileImportForm" styleClass="prepend-top"
    prependId="false">

    <div style='margin-bottom:10px'>
        <h:outputLabel value="#{msg.file_import_msg}"/>
    </div>
    <p:fileUpload id="fileImport" fileUploadListener="#{fileImport.handleFileUpload}"   
        mode="advanced"  
        update="messages"   
        multiple="true"
        label="#{msg.file_import_choose_label}" 
        uploadLabel="#{msg.file_import_upload_label}" 
        cancelLabel="#{msg.file_import_cancel_label}"       
    />  
    <p:growl id="messages" showDetail="true"/>  

</h:form>

My backing bean:

package test.boundary;

import javax.inject.Named;
import org.primefaces.event.FileUploadEvent;
import com.haslerrail.aura.common.exception.SystemException;

/**
 * BackingBean for <code>fileImport.xhtml</code> page.
 *
 */
@Named
public class FileImport implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    public void handleFileUpload(final FileUploadEvent event) throws SystemException, InterruptedException {

        if (event == null || event.getFile() == null || event.getFile().getSize() == 0) {
            System.out.println("No file");

        }
        System.out.println(event.getFile().getFileName());
        Thread.sleep(500); // wait a little to force the exception!
    }
}

The problem is, when my handleFileUpload function takes a little bit longer to parse the uploaded file (Thread.sleep(500), it throws an exception! The exception only occurs when I'm uploading more than one file at the same time.

The exception:

09:47:33,171 WARN  [org.jboss.weld.Conversation] WELD-000315 Failed to acquire conversation lock in 1,000 for Conversation with id: 1
09:47:33,180 SEVERE [org.omnifaces.exceptionhandler.FullAjaxExceptionHandler] FullAjaxExceptionHandler: An exception occurred during processing JSF ajax request. Error page '/pages/error/error.xhtml' will be shown.: org.jboss.weld.context.BusyConversationException: WELD-000322 Conversation lock timed out: 1
    at org.jboss.weld.context.AbstractConversationContext.activate(AbstractConversationContext.java:215) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.jsf.WeldPhaseListener.activateConversations(WeldPhaseListener.java:108) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.jboss.weld.jsf.WeldPhaseListener.beforePhase(WeldPhaseListener.java:85) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at com.sun.faces.lifecycle.Phase.handleBeforePhase(Phase.java:228) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:99) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:116) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:102) [primefaces-5.1.jar:5.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.omnifaces.filter.CacheControlFilter.doFilter(CacheControlFilter.java:226) [omnifaces-1.7.jar:1.7]
    at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:77) [omnifaces-1.7.jar:1.7]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:489) [jbossweb-7.0.13.Final.jar:]
    at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_75]  

For me it looks like an error in PF 5.1! Any other ideas?

@FacesComponent on shared library

I'm trying to use a custom jsf component on Websphere 8.5. The component class is annotated with @FacesComponent.

The component is on a shared lib jar on the server. I already have an faces-config inside the jar META-INF folder.

If the jar is inside my ear file it works as expected, but when its on a sharedlib it gives me "Undefined component type MyUIActionList" error.

Any ideas on how to make this work?

Access NameBinding value inside my filter

I've a filter for my REST service. A normal authentication filter.

Now I need to pass a boolean in to it. From this link I got to this point:

@NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface AuthenticationFilterBinding {

    boolean checkAccountStatus() default true;
}

And in my filter implementation I've:

@AuthenticationFilterBinding
@Provider
@Priority(FilterPriority.AUTHENTICATION_PRIORITY)
public class AuthenticationFilter extends AuthenticationAbstractFilter implements ContainerRequestFilter {

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

    @Override
    public void filter(ContainerRequestContext requestContext) {

    // Here I need to check the value of checkAccountStatus() defined in the code above.

    // How can I access that value?

    // My filter logic goes here
    }
}

On my endpoints I've something like:

@POST
@Path("/photo")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@AuthenticationFilterBinding(checkAccountStatus = false)
@ManagedAsync
public void setUserPhoto(@Suspended AsyncResponse ar, @FormDataParam("image") InputStream fileStream, @HeaderParam(Constant.HEADER_USER_ID) long userId) { 
    // ...
}

My problem is that I need to check the value of checkAccountStatus inside my filter and that is my problem here, how can I access it?

How do I define only scheduler attribues in the deploymnet descriptor, not the whole bean?

I have the following bean:

@Stateless
public class NewSessionBean {

    public void myJob() {
        System.out.println("RUN");
    }

}

and I would like to have myJob running every 10 seconds, so I have this Deployment descriptor:

<ejb-jar xmlns = "http://ift.tt/nSRXKP"
  version = "3.1"
  xmlns:xsi = "http://ift.tt/ra1lAU"
  xsi:schemaLocation = "http://ift.tt/nSRXKP
     http://ift.tt/1zK8E6E">
  <enterprise-beans>
    <session>
      <ejb-name>NewSessionBean</ejb-name>
      <ejb-class>org.test.NewSessionBean</ejb-class>
      <session-type>Stateless</session-type>
      <timer>
        <schedule>
          <second>*/10</second>
          <minute>*</minute>
          <hour>*</hour>
          <month>*</month>
          <year>*</year>
        </schedule>
        <timeout-method>
          <method-name>myJob</method-name>
       </timeout-method>
     </timer>
   </session>
 </enterprise-beans>
</ejb-jar>

And it works.

But I would like to declare only the timer in my deployment descriptor, not the whole bean so I can declare everything using annotations and parametrize the schedule.

If I remove the ejb-class or session-type my application won't load because the DD is missing this information.

Is there anyway that I can override the information for the scheduler only?

Edit: I would like to move set the parameters on the @schedule annotation to the deployment descriptor so I can change its values without needing to recompile/redeploy anything

Filter redirect not reaching to spring Controller

Hyn, I have a servlet filter,

in first step:

I am checking url from particualr action and based on that creating a new url, redirecting

String redirectURL = httpResponse.encodeRedirectURL( shopUrl + "/catalogPreview?setPreviewDate=090000");

LOG.info("RUN PREVIEW: " + redirectURL + " | IP " + httpRequest.getRemoteAddr());

httpResponse.sendRedirect(redirectURL);

return;

and return then the filter is again called with previously assemble url and let it through going through filter chain

else
{
    // proceed filters
    filterChain.doFilter(httpRequest, httpResponse);
}

the new url should reach the spring controller here is spring annotation mapping for review

@Controller
@RequestMapping(value = {"/{testId:.*}/", "/lalanium","/catalogPreview"})
public class TestPageController extends AbstractTestPageController
{

the new URL is also visible in header but getting 400 error... am I missing some step? please share

Simultaneously Iterate over multiple arrayLists in Java..Most efficiently

I am writing an API, which creates a list of User objects and then makes a call to a 3rd party webservice with that list. The 3rd party webservice then responds back with a list of UserDetails objects containing the details of the users. For ex:

Class User{
String id;
String name;
}

A list is constructed with the above User objects and then passed over to the 3rd party webservice.

List<User> users = new ArrayList <User>();

The 3rd party webservice then responds back with a list of UserDetails Objects.

Class UserDetails {
    String id;
    String email;
    String accountNumber;
    ...
    ...
    }


List<UserDetails> userDetails = new ArrayList <UserDetails>();

Now, to construct the response of my API, I construct a List of UserResponse objects which contains a mix of fields in User and UserDetails objects.

Class UserResponse{
String id;
String name;
String email;
String accountNumber;
....
...

}

To Construct this list of UserResponse objects, I have to iterate over user List and UserDetails List and then check if id's match and then construct the UserRepsonse Object and then add them to a list. The code is as below.

List <UserResponse> userResponseList = new ArrayList<UserResponse>();
for(User user : userRequest){
 for(UserDetails userDetail: userDetails){

if(user.getid().equalsIgnoreCase(userDetail.getId())){
    UserResponse userReponse = new UserResponse ();
    userReponse.setId(user.getId());
    userReponse.setName(user.getName());
    userReponse.setEmail(userDetail.getEmail());
    userReponse.setAccountNumber(userDetail.getAccountDetail());

    userResponseList.add(userReponse);

    }
 }
}

And then return the userResponseList.

The above code works. But iterating over 2 lists is what is scaring me. My API can have about 200 users in 1 request. So I send a list of 200 user objects to 3rd party service and then the 3rd party webservice responds back with a list of 200 userDetails objects.

This means I will be iterating 200*200 items in the double iterator.

Is there an better and more efficient way to perform this logic instead of iterating this many times ?

Advance Thanks..

JSF Property not found exception

can someone help out, I just don't get it, the other bean works fine, i'ts just that bean that sucks:

BEAN:

import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@SessionScoped
@Named
class FeedbackController implements Serializable {

    private static final long serialVersionUID = 1L;

    private Lecture lecture;
    private List<Feedback> filteredFeedbacks;

    public Lecture getLecture() {
        return lecture;
    }

    public void setLecture(Lecture lecture) {
        this.lecture = lecture;
    }

VIEW:

<p:dataTable var="feedback" 
             value="#{feedbackController.lecture.feedbacks}" 

ERROR: javax.el.PropertyNotFoundException: The class 'com.xxx.controller.FeedbackController' does not have a readable property 'lecture'.

Since I'm quite nooby to the subject, i dont even know what i'm possibly doing wrong. I dont get, why he is not able to access 'lecture' when the Controller is @Named and has a public getLecture() method. Also to say, is that i've got another view with the same priciple and it works fine, so i suppose to know what i'm doing.

Thanks in advance!

Collections.sort isn't sorting

I am building a web application using Java EE (although my problem is more Java based)

In a Servlet, I am getting a list of orders from the EJB. In this list of orders, there is a list of states for this order (sent, on dock, non received ...)

I want to sort this list of states by the date of the state. So I use a Collections.sort like that :

            for (Commande c : commandes) {
                c.getEtatList().sort(new Comparator<Etat>() {

                    @Override
                    public int compare(Etat o1, Etat o2) {
                        return o1.getDateEtat().compareTo(o2.getDateEtat());
                    }
                });
                c.getEtatList().sort(Collections.reverseOrder());
            }

But when I display the results, the states are not sorted.

I tried to reverse the order as you can see, but it isn't working neither.

As you also can see, I replaced the Collections.sort with the ListIWantToSort.sort. Still not working.

Any ideas on why it does not work or how I could repair it ?

How to configuring slf4j with log4j in EAR on Glassfish

I am trying to package 2 projects (ExampleWeb.war and ExampleEJb.jar) in a single EAR file. Every thing works fine except the logging thing. There is no error, but even log messages are not displayed on Glassfish server. not console no where. Here are the contents of my ear file

Example.ear
    ExampleWeb.war
    ExampleEJB.jar
    lib
        log4j.properties
        slf4j-api-1.7.12.jar
        slf4j-log4j12-1.7.12.jar
        log4j-1.2.17.jar
    META-INF
        application.xml

Contents of the application.xml are as follows

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://ift.tt/ra1lAU" xmlns="http://ift.tt/nSRXKP" xmlns:application="http://ift.tt/W0LURl" xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1evQWgx" id="Application_ID" version="6">
  <display-name>Example</display-name>
  <module>
    <web>
      <web-uri>ExampleWeb.war</web-uri>
      <context-root>/</context-root>
    </web>
  </module>
  <module>
    <ejb>ExampleEJB.jar</ejb>
  </module>
  <library-directory>lib</library-directory>
</application> 

Please note I am able to call an EJB from web project using its remote interface and that hello method successfully write a message to console, using System.out.println("hello"); how ever there is nothing happening for log.info("hello from log");

here is how I initialized the log object

//import statement
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//variable initialization
private static final Logger log = LoggerFactory.getLogger(HelloFacade.class);

Here are the contents of log4j.properties file

# Root logger option
log4j.rootLogger=FILE,console

# ------------- Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
log4j.appender.console.Threshold=INFO

# ---------------- File
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${com.sun.aas.instanceRoot}/logs/log4j.log
# Archive log files (one backup file here)
log4j.appender.FILE.MaxBackupIndex=2
# Control the maximum log file size
log4j.appender.FILE.MaxFileSize=1000KB
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
log4j.appender.FILE.Threshold=INFO

Point to be noted

  1. There is no slf4*.jar can be found in GlassFish except with in application deployed folder.
  2. There is no other log4j.properties in GlassFish except with in application deployed folder.

I have tried lot of things but unable to figure out the logging thing Please help me to fix it.

Multiple test I have ran multiple test where I have removed jar files and placed them in ear's lib folder, kept the log4j.properties file in almost every folder of EAR file (rootfolder, classes folder, lib folder, META-INFO folder) but it has no impact at all, No error and no logging.

I would be really amazed if someone does not know how to achieve this (logging, EAR[with multiple jar and war files], and Glassfish)

Could not resolve artifact error with Maven

When I build a module using Maven, I get the following error: Can anyone please let me know what this error means exactly?

[ERROR] Failed to execute goal com.dsths.common:container-maven-plugin:1.2.1:dis
t (build-distributions) on project pmDist: Unable to create distribution: Could
not resolve artifact: com.dsths.awdprovidermatching:pmConfig:jar:default-externa
l-jetty:1.0.2-SNAPSHOT:COMPILE -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://ift.tt/1sqyjQT
xception

Jboss Failed to instantiate class "org.jboss.logmanager.handlers.PeriodicRotatingFileHandle

When I tried jbosseap6.3 install as service. I got below error. Anyone have any idea on the below error. Any one shed light means it is very helpful for me.

java.lang.IllegalArgumentException: Failed to instantiate class "org.jboss.logmanager.handlers.PeriodicRotatingFileHandler" for handler "FILE"
    at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:119)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.doPrepare(LogContextConfigurationImpl.java:338)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.prepare(LogContextConfigurationImpl.java:291)
    at org.jboss.logmanager.config.LogContextConfigurationImpl.commit(LogContextConfigurationImpl.java:300)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:542)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:97)
    at org.jboss.as.logging.logmanager.ConfigurationPersistence.configure(ConfigurationPersistence.java:149)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:300)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:262)
    at java.util.logging.LogManager$3.run(LogManager.java:399)
    at java.util.logging.LogManager$3.run(LogManager.java:396)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.readPrimordialConfiguration(LogManager.java:396)
    at java.util.logging.LogManager.access$800(LogManager.java:145)
    at java.util.logging.LogManager$2.run(LogManager.java:345)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.ensureLogManagerInitialized(LogManager.java:338)
    at java.util.logging.LogManager.getLogManager(LogManager.java:378)
    at org.jboss.modules.Main.main(Main.java:443)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:117)
    ... 18 more
Caused by: java.io.FileNotFoundException: C:\jboss-eap-6.3\standalone\log\server.log (The process cannot access the file because it is being used by another process)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at org.jboss.logmanager.handlers.FileHandler.setFile(FileHandler.java:154)
    at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.setFile(PeriodicRotatingFileHandler.java:105)
    at org.jboss.logmanager.handlers.FileHandler.setFileName(FileHandler.java:192)
    at org.jboss.logmanager.handlers.FileHandler.<init>(FileHandler.java:122)
    at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.<init>(PeriodicRotatingFileHandler.java:73)
    ... 23 more
Shutdown JBossEAP6.3.0 service [2015-05-29 09:58:27]

wicket 6 model window set pageparameters onClose

For a project I use wicket 6.17.0. In this project is a page, invullenPage, where users can answer a question. That question will be built on a different page, aanmakenPage. The aanmakenPage, several questions created by a dynamic form with Ajax wicket. And on this page, there is a possibility to get a preview of the complete page, on the basis of questions completed in the dynamic form. And i want to use invullenPage for that preview.

This I wanted to do with opening a new tab. However, this was not advised in different places because ajax open a new page would not handle well.

Now I want to do with Modal Window, only I run into the problem that when I come after closing the modal window on a page that I lost all the values of the form and page parameters.

I try to solve by imparting a different parameter and storing the model form in the session only when the page is re-renderd than the page parameters are lost.

As a result, he can thus also not be read that there is an object in the session.

How can I solve this problem the best.

I meanwhile tried to turn the page parameters CloseButton Callback class of Modal Window, only it is never invoked.

If more information is needed than I know.

Thanks,

Harm

Set session variable using JSTL and accessing it in servlet/controller class

If I set session variable using JSTL like this:

<c:set var="para" value="${CLIENT_LOGO}" scope="session"  />

Then how can I access the variable "para" in a servlet/controller class?

I tried the below code variations, but none worked.

request.getAtrribute("para") 


request.getSession().getAtrribute("para") 

Note: I'm not looking for a solution to print the value in a jsp something like:

<c:out value="${sessionScope.para}" />

But instead, I would like to know whether any solution possible to get it in Java class.

WLS cannot deploy from console

Trying to deploy a WAR from netbeans to WebLogic works, but from the web console and command line the app would throw stupid java exceptions like:

The import javax.servlet.http.HttpServletRequest cannot be resolved
String cannot be resolved to a type

Please help

Tomcat user has principal role but request.isUserInRole() says otherwise

In tomcat-users.xml is defined user and roles:

<user username="admin" password="admin" roles="user,admin,APP_ADMIN"/>

and application security is defined as:

<security-constraint>
        <web-resource-collection>
                <web-resource-name>Dynamic pages</web-resource-name>
                <url-pattern>*.jsp</url-pattern>
        </web-resource-collection>
        <auth-constraint>
                <description>These are the roles who have access.</description>
                <role-name>*</role-name>
        </auth-constraint>
        <user-data-constraint>
                <description></description>
                <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>

But when I login as admin into application it gives me always HTTP 403 not authorized.
I checked roles with JSP scriplet:

out.write(request.getUserPrincipal().toString()); 

And it prints:

User username="admin", roles="user,admin,APP_ADMIN"

But when i check isUserInRole:

out.write(request.isUserInRole("APP_ADMIN") ? "Yep" : "nope");

Gets:

nope

Tomcat version is 7.0.55

Soap11Factory NoClassDefFoundError occurs when using weblogic-application.xml

I am using an EAR to deploy in Weblogic 12c which contains a war used for SOAP calls. I have added a weblogic-application.xml which contains the following settings

 <?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://ift.tt/1MZYFRt" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1xdJq1T http://ift.tt/1MZYFRt http://ift.tt/1MZYLs4">
<wls:prefer-application-packages>
        <wls:package-name>org.slf4j.*</wls:package-name>
</wls:prefer-application-packages>

(Note : This change is done so that I get to use the slf4j jar that i have imported in maven instead of the slf4j jar packaged with weblogic 12c. This is a common issue)

Now on making Soap Calls to my server, I get the following Error in my Logs

java.lang.NoClassDefFoundError: org/apache/axiom/soap/impl/dom/soap11/SOAP11Factory
at org.apache.axis2.saaj.MessageFactoryImpl.createMessage(MessageFactoryImpl.java:108)
at org.apache.cxf.binding.soap.saaj.SAAJInInterceptor.handleMessage(SAAJInInterceptor.java:175)
at org.apache.cxf.jaxws.handler.soap.SOAPMessageContextImpl.getMessage(SOAPMessageContextImpl.java:78)
at org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor.getOpQName(SOAPHandlerInterceptor.java:322)
at org.apache.cxf.jaxws.handler.AbstractJAXWSHandlerInterceptor.setupBindingOperationInfo(AbstractJAXWSHandlerInterceptor.java:111)
Truncated. see log file for complete stacktrace

Normally I'd add the jar as a maven dependency in these situations , but the above issue occurs only when i add the weblogic-application.xml in my EAR. It works fine when i redeploy the ear without the weblogic xml file.

Any idea why this Error is connected with the weblogic-application.xml file?

BeanCreationException: Error creating bean with name: Injection of autowired dependencies failed;

I am getting the following error stack when trying to deploy a war using a jetty server I have written.

INFO : jetty.StartJetty - starting jetty using war file ..\serialisation-preview-service\target\serialisation-preview-service-1.3.0-SNAPSHOT.war
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-log4j12/1.6.2/slf4j-log4j12-1.6.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://ift.tt/1f12hSy for an explanation.
INFO : org.eclipse.jetty.util.log - jetty-7.2.2.v20101205
INFO : org.eclipse.jetty.util.log - Extract jar:file:/U:/Code/Serialisation_Fresh/serialisation-preview-service/target/serialisation-preview-service-1.3.0-SNAPSHOT.war!/ to C:\Users\username\AppData\Local\Temp\jetty-0.0.0.0-8080-serialisation-preview-service-1.3.0-SNAPSHOT.war-_-any-\webapp
INFO : / - Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri May 22 09:02:37 BST 2015]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d75e99: defining beans []; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1958 ms
WARN : org.eclipse.jetty.util.log - FAILED jsp: java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
INFO : / - Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Fri May 22 09:02:39 BST 2015]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/servlet-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [preview-service-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [dao-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from class path resource [placeit.properties]
INFO : org.springframework.beans.factory.config.PropertyOverrideConfigurer - Loading properties file from class path resource [preview-server-overrideDEV.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d61b48: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,myController,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,previewServerPropertyOverride,org.springframework.beans.factory.config.PropertyOverrideConfigurer#0,labelService,placeit.SerialDataCSVGenerator#0,placeit.DataMatrixGenerator#0,org.springframework.expression.spel.standard.SpelExpressionParser#0,printers,ftp.FtpEmulator#0,placeitPreviewProcess,placeitLabelProcess,placeitHapaProcess,hgdlCompiler,util.DateServiceImpl#0,org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,org.springframework.scheduling.support.PeriodicTrigger#0,poller,JobFileCreator,rendezvous,PreviewService,org.springframework.integration.transformer.HeaderEnricher#0,org.springframework.integration.transformer.MessageTransformingHandler#0,writeFiles,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,writeFiles2,limitJobs,org.springframework.integration.router.RecipientListRouter#0,writeJobRouter,org.springframework.integration.config.ServiceActivatorFactoryBean#0,createJobFile,createJobFileSA,org.springframework.integration.transformer.HeaderEnricher#1,org.springframework.integration.transformer.MessageTransformingHandler#1,writeJobFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#1,writeJobFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#0,writeJobFile2.adapter,org.springframework.integration.transformer.HeaderEnricher#2,org.springframework.integration.transformer.MessageTransformingHandler#2,writeFmtFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#2,writeFmtFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#1,writeFmtFile2.adapter,org.springframework.integration.config.ServiceActivatorFactoryBean#1,waitForReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#3,generatedPreviewFile,org.springframework.integration.file.config.FileListFilterFactoryBean#0,org.springframework.integration.file.config.FileReadingMessageSourceFactoryBean#0,generatedPreviewFile.adapter,org.springframework.integration.config.TransformerFactoryBean#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#4,org.springframework.integration.config.ServiceActivatorFactoryBean#2,deliverReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#5,aggregationDaoImpl,notificationDaoImpl,parametersDaoImpl,serialisationDaoImpl,templatePreviewDaoImpl,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,entityManagerFactory,org.springframework.jdbc.core.JdbcTemplate#0,org.springframework.jdbc.core.simple.SimpleJdbcTemplate#0,dataSource,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@d75e99
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Initializing ExecutorService  'taskScheduler'
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d61b48: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,myController,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,previewServerPropertyOverride,org.springframework.beans.factory.config.PropertyOverrideConfigurer#0,labelService,placeit.SerialDataCSVGenerator#0,placeit.DataMatrixGenerator#0,org.springframework.expression.spel.standard.SpelExpressionParser#0,printers,ftp.FtpEmulator#0,placeitPreviewProcess,placeitLabelProcess,placeitHapaProcess,hgdlCompiler,util.DateServiceImpl#0,org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,org.springframework.scheduling.support.PeriodicTrigger#0,poller,JobFileCreator,rendezvous,PreviewService,org.springframework.integration.transformer.HeaderEnricher#0,org.springframework.integration.transformer.MessageTransformingHandler#0,writeFiles,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,writeFiles2,limitJobs,org.springframework.integration.router.RecipientListRouter#0,writeJobRouter,org.springframework.integration.config.ServiceActivatorFactoryBean#0,createJobFile,createJobFileSA,org.springframework.integration.transformer.HeaderEnricher#1,org.springframework.integration.transformer.MessageTransformingHandler#1,writeJobFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#1,writeJobFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#0,writeJobFile2.adapter,org.springframework.integration.transformer.HeaderEnricher#2,org.springframework.integration.transformer.MessageTransformingHandler#2,writeFmtFile,org.springframework.integration.config.ConsumerEndpointFactoryBean#2,writeFmtFile2,org.springframework.integration.file.config.FileWritingMessageHandlerFactoryBean#1,writeFmtFile2.adapter,org.springframework.integration.config.ServiceActivatorFactoryBean#1,waitForReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#3,generatedPreviewFile,org.springframework.integration.file.config.FileListFilterFactoryBean#0,org.springframework.integration.file.config.FileReadingMessageSourceFactoryBean#0,generatedPreviewFile.adapter,org.springframework.integration.config.TransformerFactoryBean#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#4,org.springframework.integration.config.ServiceActivatorFactoryBean#2,deliverReply,org.springframework.integration.config.ConsumerEndpointFactoryBean#5,aggregationDaoImpl,notificationDaoImpl,parametersDaoImpl,serialisationDaoImpl,templatePreviewDaoImpl,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,entityManagerFactory,org.springframework.jdbc.core.JdbcTemplate#0,org.springframework.jdbc.core.simple.SimpleJdbcTemplate#0,dataSource,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@d75e99
INFO : org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler - Shutting down ExecutorService 'taskScheduler'
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.TemplatePreviewDao controllers.PreviewHttpController.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:609)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:571)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:623)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:491)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:432)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:432)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:260)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:762)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:244)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1181)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:584)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:496)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:226)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:93)
    at org.eclipse.jetty.server.Server.doStart(Server.java:243)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55)
    at jetty.StartJetty.main(StartJetty.java:56)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.TemplatePreviewDao controllers.PreviewHttpController.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:504)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 32 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'templatePreviewDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:343)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:476)
    ... 34 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [dao-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:531)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:497)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:658)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:631)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:147)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:340)
    ... 45 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [dao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    ... 61 more
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'password' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'password' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1031)
    at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:902)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
    ... 69 more

Here is the TemplatePreview class it complains about with an EntityManager define:

@Repository
public class TemplatePreviewDaoImpl implements TemplatePreviewDao {
    @PersistenceContext private EntityManager entityManager;
    // ...
}

Here is one of my project context files with bean declarations:

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

    <tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>

    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="persistenceXmlLocation" value="classpath:/META-INF/persistenceOracle.xml"/>
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        </property>
    </bean>

    <bean class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource"/>
    </bean>

    <bean class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
    <constructor-arg ref="dataSource"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
        <property name="jndiName" value="java:comp/env/DS_SERIALISATION"/>
    </bean>

And the contents of the properties file containing the information for the dataSource:

dataSource.url=jdbc:oracle:thin:@correct_url
dataSource.username=************
dataSource.password=************
dataSource.driverClassName=oracle.jdbc.OracleDriver
entityManagerFactory.persistenceXmlLocation=classpath:/META-INF/persistenceOracle.xml
rendezvous.timeout=-1

The persistenceOracle xml file mentioned here is also accessible so I don't think it's a problem there. I have no idea why Spring cannot autowire the dependencies or why it is having trouble with my dataSource. Any help with this would be much appreciated.

EDIT

My override file exists in a separate project but I can't be sure my war project knows about it. The project that contains the properties file does not have a src folder or anything so I can't add it to the classpath of the war project.

override properties file

I pass DEV as a VM argument in my run configuration which gets appended when looking for the correct properties file.