Send mail in Apache TomEE

Make javax.mail and impl as maven scope provided, as TomEE comes with geronimo mail implementation.

Also use resource injection of mail session:

(If mail account is Gmail, turn ON ‘Allow less secure apps’)

In Tomee.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <!-- see -->
    <!-- activate next line to be able to deploy applications in apps -->
    <!-- <Deployments dir="apps" /> -->
    <Resource id="tomee/mail/GMailSMTP" type="javax.mail.Session">
    mail.smtp.user=<!-- your email address -->
    password=<!-- your password, and not 'mail.smtp.password' -->

Injection of resource:

@Path(value = "workline")
public class MailService {
    @Resource(mappedName = "java:comp/env/tomee/mail/GMailSMTP")
    private Session smtpSession;
    public boolean sendMail() throws NamingException {
        final Message message = new MimeMessage(this.smtpSession);
        try {
            message.setRecipients(Message.RecipientType.TO, new Address[]{
                new InternetAddress("")
            message.setSubject("Email from TomEE");
            message.setSentDate(new Date());
            message.setText("Email from TomEE");
        } catch (Exception e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
            return false;
        return true;

A raw implementation:

package com.origami.rpp.util;

import com.origami.config.SisVars;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

 * @author Origami
public class Email {

    protected List<File> adjuntos = new ArrayList<>();
    protected String usuarioCorreo = SisVars.correo;
    protected String password = SisVars.pass;
    protected String rutaArchivo1;
    protected String nombreArchivo1;
    protected String rutaArchivo2;
    protected String nombreArchivo2;
    protected String destinatario;
    protected String copiaOcultaBCC;
    protected String copiaCC;
    protected String asunto;
    protected String mensaje;

    public Email(String destinatario, String copiaOcultaBCC, String copiaCC, String asunto, String mensaje, List<File> files) {
        this.destinatario = destinatario;
        this.copiaOcultaBCC = copiaOcultaBCC;
        this.copiaCC = copiaCC;
        this.asunto = asunto;
        this.mensaje = mensaje;
        if(files != null) this.adjuntos = files;

    public Email(String destinatario, String asunto, String mensaje, List<File> files) {
        this(destinatario, null, null, asunto, mensaje, files);

    public boolean sendMail() {
        try {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("", SisVars.smtp_Host);
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.smtp.port", SisVars.smtp_Port);
            props.setProperty("mail.smtp.user", usuarioCorreo);
            props.setProperty("mail.smtp.auth", "true");
            Session session = Session.getInstance(props, null);
            //CUERPO DEL MENSAJE
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(usuarioCorreo, "EMPRESA PUBLICA MUNICIPAL DEL REGISTRO DE LA PROPIEDAD DEL CANTON PORTOVIEJO EP"));
            mimeMessage.setSentDate(new Date());
            mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(destinatario));
            if (copiaOcultaBCC != null) {
                mimeMessage.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(copiaOcultaBCC));
            if (copiaCC != null) {
                mimeMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(copiaCC));
            //TEXTO DEL MENSAJE
            MimeBodyPart texto = new MimeBodyPart();
            Multipart multipart = new MimeMultipart();
            MimeBodyPart file;
            for (File f : adjuntos ) {
                file = new MimeBodyPart();
            // ENVIAR MENSAJE
            Transport transport = session.getTransport("smtp");
            transport.connect(usuarioCorreo, password);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        } catch (MessagingException ex) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, e);
        return true;


Fix JMX RMI port configuration

Set the following ports in java command line:

Example on unique port 9229:

In Tomcat / TomEE set them in bin/ file:

export CATALINA_OPTS="$CATALINA_OPTS -server -Xmx6000m -Xms512m -XX:MaxPermSize=400m -Djava.rmi.server.hostname="

export JAVA_OPTS="-client -Xms8m -Xmx128m -XX:MaxPermSize=64m"

Due to a bug this doesnt works in java versions <= 1.7.0_51. Please upgrade the java/JDK version.


Simple JSF View Scope for Spring

Please use:

Light version of:

without destruction callback listener support



package org.nkey.primefaces.scopes.test.spring.scope;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PreDestroyViewMapEvent;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

 * @author m.nikolaev Date: 21.11.12 Time: 0:37
public class ViewScope implements Scope, Serializable{
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewScope.class);
    public Object get(String name, ObjectFactory objectFactory) {
        final Map viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();

		if (viewMap.containsKey(name)) {
			Object bean = viewMap.get(name);			

			// // restore a transient autowired beans after re-serialization bean
			//WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext();
			//AutowireCapableBeanFactory autowireFactory = webAppContext.getAutowireCapableBeanFactory();
			//if (webAppContext.containsBean(name)) {
				// Reconfigure resored bean instance.
				//bean = autowireFactory.configureBean(bean, name);
			// // end restore
			return bean;
		} else {
			final Object object = objectFactory.getObject();
			viewMap.put(name, object);

			return object;

    public Object remove(String name) {
        return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);

    public String getConversationId() {
        return null;

    public void registerDestructionCallback(String name, Runnable callback) {

    public Object resolveContextualObject(String key) {
        return null;

package org.nkey.primefaces.scopes.test.spring.scope;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;

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

 * @author m.nikolaev Date: 21.11.12 Time: 1:01
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface SpringViewScoped {



NoSuchMethodError when having an Map abstract class extending abstractmap in EclipseLink

Entity Bean inheritance definition

Base superclass extending IdentityhashMap:

public class EntityModel<K extends String, V extends Object> extends IdentityHashMap<String, Object>{

    public EntityModel() {

Entity JPA:

@Table(name = "acl_usuario")
@SequenceGenerator(name = "global_seq", sequenceName = "global_seq", allocationSize = 20)
public class Usuario extends EntityModel{

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "global_seq")
    @Basic(optional = false)
    @Column(name = "id", nullable = false)
    protected Long id;

    @Basic(optional = false)
    @Column(name = "username", length = 50, nullable = false)
    protected String username;

    @Basic(optional = false)
    @Column(name = "pass", length = 20, nullable = false)
    protected String pass;

    @Basic(optional = false)
    @Column(name = "habilitado", nullable = false)
    protected Boolean habilitado;

    @JoinColumn(name = "rol", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Rol rol;

    @OneToMany(mappedBy = "supervisor", fetch = FetchType.LAZY)
    private Collection<OrdenTrabajo> supervisorCollection;

    @OneToMany(mappedBy = "responsable", fetch = FetchType.LAZY)
    private Collection<OrdenTrabajo> responsableCollection;

    public Usuario() {

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;

    public String getPass() {
        return pass;

    public void setPass(String pass) {
        this.pass = pass;

    public Boolean getHabilitado() {
        return habilitado;

    public void setHabilitado(Boolean habilitado) {
        this.habilitado = habilitado;

    public Rol getRol() {
        return rol;

    public void setRol(Rol rol) {
        this.rol = rol;

    public Collection<OrdenTrabajo> getSupervisorCollection() {
        return supervisorCollection;

    public void setSupervisorCollection(Collection<OrdenTrabajo> supervisorCollection) {
        this.supervisorCollection = supervisorCollection;

    public Collection<OrdenTrabajo> getResponsableCollection() {
        return responsableCollection;

    public void setResponsableCollection(Collection<OrdenTrabajo> responsableCollection) {
        this.responsableCollection = responsableCollection;

    public int hashCode() {
        int hash = 3;
        hash = 59 * hash + ( != null ? : 0);
        return hash;

    public boolean equals(Object obj) { 
        if (obj == null) {
            return false;
        if (getClass() != obj.getClass()) {
            return false;
        final Usuario other = (Usuario) obj;
        if ( != && ( == null || ! {
            return false;
        return true;


With Eclipselink default configuration got NoSuchMethodError.

The fix

Disable eclipselink.weaving.internal configuration. (

In persistence.xml

  <property name="eclipselink.weaving.internal" value="false"/>

In property map

propertiesMap.put(PersistenceUnitProperties.WEAVING_INTERNAL, "false");

In Spring

<bean id="jpaVendorAdapter" class="de.mischur.library.utils.ExtendedEclipseLinkJpaVendorAdapter">
    <property name="weavingInternal" value="false">

Include facelet programatically JSF

The purpose is to use programmatically, then you should be using FaceletContext#includeFacelet() . Assuming that you’re inside your custom component:

FacesContext facesContext = FacesContext.getCurrentInstance();
FaceletContext faceletContext = (FaceletContext) facesContext.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
faceletContext.includeFacelet(this, "include.xhtml"); // this is your current UIComponent.

Here’s another kickoff example which demonstrates dynamic include by command button:

    <h:commandButton value="include" action="#{bean.include}" />
<h:panelGroup id="include" />


public void include() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    FaceletContext faceletContext = (FaceletContext) facesContext.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
    faceletContext.includeFacelet(facesContext.getViewRoot().findComponent("foo"), "include.xhtml");


Include composite component programatically JSF

use FaceletContext#includeFacelet() to include the composite component resource in the given parent.

public static void includeCompositeComponent(UIComponent parent, String libraryName, String resourceName, String id) {
    // Prepare.
    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    FaceletContext faceletContext = (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);

    // This basically creates <ui:component> based on <composite:interface>.
    Resource resource = application.getResourceHandler().createResource(resourceName, libraryName);
    UIComponent composite = application.createComponent(context, resource);
    composite.setId(id); // Mandatory for the case composite is part of UIForm! Otherwise JSF can't find inputs.

    // This basically creates <composite:implementation>.
    UIComponent implementation = application.createComponent(UIPanel.COMPONENT_TYPE);
    composite.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, implementation);

    // Now include the composite component file in the given parent.
    parent.pushComponentToEL(context, composite); // This makes #{cc} available.
    try {
        faceletContext.includeFacelet(implementation, resource.getURL());
    } catch (IOException e) {
        throw new FacesException(e);
    } finally {

Imagine that you want to include <my:testComposite id="someId"> from URI xmlns:my="", then use it as follows:

includeCompositeComponent(parent, "mycomponents", "testComposite.xhtml", "someId");

This has also been added to JSF utility library OmniFaces as Components#includeCompositeComponent() (since V1.5).

Since JSF 2.2, the ViewDeclarationLanguage class got a new createComponent() method taking the taglib URI and tag name which could also be used for this purpose. So, if you’re using JSF 2.2, the approach should be done as follows:

public static void includeCompositeComponent(UIComponent parent, String taglibURI, String tagName, String id) {
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent composite = context.getApplication().getViewHandler()
        .getViewDeclarationLanguage(context, context.getViewRoot().getViewId())
        .createComponent(context, taglibURI, tagName, null);

Imagine that you want to include <my:testComposite id="someId"> from URI xmlns:my="", then use it as follows:

includeCompositeComponent(parent, "", "testComposite", "someId");



JPA Global Sequence provider EJB Singleton

package com.origami.censocat.service;

import java.util.concurrent.atomic.AtomicLong;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

 * @author Fernando
public class GlobalSequenceProvider implements GlobalSequenceProviderLocal {
    @PersistenceContext(unitName = "CensoCat_PU")
    private EntityManager em;
    private Long actualId;
    private Long limitId;
    private final Long interval = 20L;

    public GlobalSequenceProvider() {
    protected Boolean esDisponible(){
        if(actualId==null || actualId>=limitId){
            return false;
        return true;
    public Long getNextId(){
            // obtener nuevo intervalo de secuencia
        return actualId;
    protected void genNextInterval(){
        Query q = em.createNativeQuery("select nextval('global_seq')");
        actualId = (Long)q.getSingleResult();
        limitId = actualId + interval;

Apache Tomee 1.7 Plume Datasource configuration

In this example we will configure an postgresql datasource.

First download an place in /lib folder the postgresql JDBC driver jar

Open /conf/tomee.xml and put the datasource resource block:

<?xml version="1.0" encoding="UTF-8"?>
  <!-- see -->
  <Resource id="censocat_db" type="DataSource">
    #  PostgreSQL connection
    JdbcDriver   org.postgresql.Driver
    JdbcUrl  jdbc:postgresql://localhost/censocat
    UserName     sisapp
    Password     sis98

Persistence.xml configuration:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">
  <persistence-unit name="CensoCat_PU" transaction-type="JTA">
      <property name="eclipselink.ddl-generation" value="create-tables"/>
      <property name="eclipselink.ddl-generation.output-mode" value="database"/>

EJB injection of EM:

    @PersistenceContext(unitName = "CensoCat_PU")
    private EntityManager entityManager;

Common DataSource Configurations share [gp] share [fb] share [tw] share [pin] contribute
See the DataSource Configuration for details on all configuration options for DataSources.

The drivers are included with OpenEJB 3.0 and HSQLDB is the default database.

<Resource id="HSQLDB Database" type="DataSource">
    JdbcDriver org.hsqldb.jdbcDriver
    JdbcUrl jdbc:hsqldb:file:hsqldb
    UserName sa

Derby (Embedded)

<Resource id="Derby Database" type="DataSource">
    #Embedded Derby example

    JdbcDriver org.apache.derby.jdbc.EmbeddedDriver
    JdbcUrl jdbc:derby:derbyDB;create=true
    UserName admin
    Password pass


<Resource id="MySQL Database" type="DataSource">
    #  MySQL example
    #  This connector will not work until you download the driver at:

    JdbcDriver  com.mysql.jdbc.Driver
    JdbcUrl jdbc:mysql://localhost/test
    UserName    test


<Resource id="Oracle Database" type="DataSource">
    #  Oracle example
    #  This connector will not work until you download the driver at:
    JdbcDriver  oracle.jdbc.OracleDriver
    JdbcUrl jdbc:oracle:thin:@localhost:1521:orcl
    UserName    scott
    Password    tiger


<Resource id="OracleXA Database" type="DataSource">
    #  OracleXA example
    #  This connector will not work until you download the driver at:
    JdbcDriver  oracle.jdbc.xa.client.OracleXADataSource
    JdbcUrl jdbc:oracle:thin:@localhost:1521:orcl
    UserName    scott
    Password    tiger


<Resource id="PostgreSQL Database" type="DataSource">
    #  PostgreSQL example
    #  This connector will not work until you download the driver at:
    JdbcDriver   org.postgresql.Driver
    JdbcUrl  jdbc:postgresql://localhost/test
    UserName     postgres
    Password     pass


<Resource id="InstantDB Database" type="DataSource">
    #  InstantDB example
    JdbcDriver   org.enhydra.instantdb.jdbc.idbDriver
    JdbcUrl  jdbc:idb:conf/
    UserName     Admin
    Password     pass

Internally, from TomEE 1.5.0, JDBC pools are managed via Tomcat-pool. You can still switch back to Apache Commons DBCP by adding the following property: DataSourceCreator dbcp. To get the full list of available configuration properties, have a look to Apache Commons DBCP configuration.

Netbeans fails to start Apache Tomee 1.7

In server.xml, remove the server=”Apache TomEE” attribute from the connector:

<Connector port="8080" protocol="HTTP/1.1"
           redirectPort="8443" xpoweredBy="false"
           server="Apache TomEE" />

In bin/catalina.bat: line 179 and 184 change:








(Basically remove the “”)