domingo, 23 de dezembro de 2007

mostrar sql hibernate no log

propriedade: hibernate.show_sql = true
Adicionar esta configuração no log4j:

log4j.logger.org.hibernate=DEBUG, SQL_APPENDER
log4j.logger.org.hibernate.type=DEBUG, SQL_APPENDER
retirado de http://www.javalobby.org/java/forums/t44119.html

sábado, 10 de novembro de 2007

SEVERE: Exception sending context destroyed event to listener instance of class org.apache.myfaces.webapp.StartupServletContextListener

Erro:

SEVERE: Exception sending context destroyed event to listener instance of class org.apache.myfaces.webapp.StartupServletContextListener
java.lang.LinkageError: loader constraint violation: loader (instance of org/apache/catalina/loader/WebappClassLoader) previously initiated loading for a different type with name "javax/el/ExpressionFactory"
   at java.lang.ClassLoader.defineClass1(Native Method)
   at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)

Solução: Existe uma classe, provavelmente as que controlam a integracao das expressoes de linguagem com as expressoes de ligacao duplicadas. ocorre quando utiliza .jar's destas classes no tomcat 6 que já possui esta integracao

terça-feira, 9 de outubro de 2007

java.util.MissingResourceException: Can't find bundle for base name

java.util.MissingResourceException: Can't find bundle for base name com.sun.el.Messages,

solução:

crie o arquivo com.sun.el.Messages.properties

terça-feira, 18 de setembro de 2007

Default Action for a JSF Form

Description

The current JSF-RI implementation does not allow to you to define the default action in case the user submits the form by pressing the Enter key instead of clicking the action button explicitly. As a result, the form action becomes undefined and the current page is just reloaded. Developers have to write additional javascript code to prevent such undesirable behavior.

The j4j:defaultAction custom component included in the j4j tag libraries allows you to define the default action for a form by adding as a child tag to the commandButton tag.

PS: This component was writen before even first version fo Firefox is released. This is a code that works also in FireFox. function trapEnter(evt) { var keycode; if (evt) ; else if (window.event) evt = window.event; else if (event) evt = event; else return true; if (evt.charCode) keycode = evt.charCode; else if (evt.keyCode) keycode = evt.keyCode; else if (evt.which) keycode = evt.which; else keycode = 0; if (keycode == 13) { document.getElementById('form:save').click(); return false; } else return true; }

How to Download

Download the compiled code using this URL: j4j.jar (4 K)

How to Use

1. Put the j4j.jar file in the WEB-INF/lib folder of your project.

2. Add the following declaration at the top of the page:

... taglib uri="http://javascript4jsf.dev.java.net/" prefix="j4j" ...

3. Add the j4j:defaultAction component as an empty child element of the commandButton that you want to make a default button.

Source Code

Here is the part of the library structure in j4j.jar that relates to this component:

The boldfaced code shows how to insert a reference to the proxy component in the faces-config.xml file:


   
 
org.j4j.defaultAction
org.j4j.components.UIDefaultAction


Here is the content of the j4j.tld file:


retirados de http://www.jsftutorials.net/defaultActionTag.html

segunda-feira, 17 de setembro de 2007

Dicas para execução do eclipse

retirado de http://wiki.eclipse.org/index.php/FAQ_How_do_I_run_Eclipse%3F

Eclipse 3.3

When you unzip the Eclipse SDK, it creates a base install directory called eclipse. The directory layout looks something like this:

   eclipse/
     features/   ''the directory containing Eclipse features''
     plugins/   ''the directory containing Eclipse plugins''
     eclipse.exe  ''platform executable''
     eclipse.ini
     eclipsec.exe              ''(windows only) console executable''
     epl-v10.html  ''the EPL license''
     eclipse.ini 
     jre/   ''the JRE to run Eclipse with''
     notice.html 
     readme 

You can start Eclipse by running eclipse.exe on Windows or eclipse on other platforms. This small launcher essentially finds and loads the JVM that is on your PATH. On Windows, the eclipsec.exe console executable can be used for improved command line behaviour.

Alternatively, you can launch Eclipse by directly invoking the JVM as follows:

   java -jar eclipse/plugins/org.eclipse.equinox.launcher_1.0.0.v20070606.jar

NOTE: The version of org.eclipse.equinox.launcher in the above command must match the version actually shipped with Eclipse. For more details on launching Eclipse using Java (not eclipse.exe) with the 3.3 launcher, see Starting Eclipse Commandline With Equinox Launcher.

Dicas JavaServer Faces

retirados de: http://www.oracle.com/webapps/online-help/jdeveloper/10.1.3?topic=sf_ajsfwebxml_html

Part of a JSF application's configuration is determined by the contents of its J2EE application deployment descriptor, WEB-INF/web.xml . JDeveloper automatically creates the web.xml file when you create a JSF page or document, and initializes the JSF configuration to default settings. You can then modify these settings for your particular application.

For more information about the web.xml file, see About Web Module Runtime Configuration. For information about configuring web.xml for ADF Faces, see About Configuring web.xml for ADF Faces.

Three web.xml elements contain JSF-related configuration settings:

  • <context-param> - sets parameters for the JSF application
  • <servlet> - maps the JSF servlet to a symbolic name
  • <servlet-mapping> - maps the JSF servlet symbolic name to a URL pattern
Use to set application-wide JSF parameters. The syntax is:

    parmName
   parmValue        
where
parmName
is the parameter's symbolic name
parmValue
is the value you wish to set for the parameter

The following parameters are available in JSF:

javax.faces.CONFIG_FILES
Use: Specifies paths to JSF application configuration resource files. Value: A comma-separated list of application-context-relative paths.
javax.faces.DEFAULT_SUFFIX
Use: Specifies a file extension (suffix) for JSP pages that contain JSF components. The default is .jsp . Value: A file extension
javax.faces.LIFECYCLE_ID
Use: Selects a lifecycle identifier other than the default set by the javax.faces.lifecycle.LifecycleFactory.DEFAULT_LIFECYCLE constant. Value: Lifecycle identifier
javax.faces.STATE_SAVING_METHOD
Use: Selects a state saving method. Value: Either server or client. The default is server, which stores the application's view state on the server. If you select client, JSF stores the view state on the browser client.
Use: Maps the JSF servlet javax.faces.webapp.FacesServlet to a symbolic name. Value: Symbolic name. For example, to use myServlet as the symbolic name, add the following to web.xml:

 myServlet
 javax.faces.webapp.FacesServlet
        
Use: Maps URL patterns to the JSF servlet's symbolic name. Value: URL pattern. You can use either a path prefix or extension suffix pattern:
path prefix
provides a mapping to the JSF servlet. All URLs in the application would contain this prefix in their path. For example, http://localhost:8080/login/faces/index.jsp

 faces-servlet-name
 /faces/*
              
extension suffix
provides an extension to which the servlet maps JSPs that include JSF content. For example, http://localhost:8080/login/index.faces

 faces-servlet-name 
 *.faces
             

quinta-feira, 16 de agosto de 2007

trabalhando com latex

Passo 1: Instale o latex:

miktex: http://www.miktex.org/
TEXLive: http://www.tug.org/texlive/
Passo 2: Instale o gostscript e o gsViewer:

http://www.cs.wisc.edu/~ghost/index.html
Passo 3: Instale o corretor ortográfico aspell:

programa: http://ftp.gnu.org/gnu/aspell/w32/Aspell-0-50-3-3-Setup.exe
dicionário: http://ftp.gnu.org/gnu/aspell/w32/Aspell-pt-0.50-2-3.exe
Plugin Eclipse: url: http://texlipse.sourceforge.net/

profile no firefox

execute o firefox com a seguinte linha de comando:

firefox.exe -ProfileManager

terça-feira, 7 de agosto de 2007

CVS

Criar novo repositório no cvs

  • execute o comando:
    cvs -d repdir init
(repdir é nome do seu novo repositório)

Links úteis

domingo, 5 de agosto de 2007

Exemplo completo com EJB 3

Criando o Entity Bean

package teste;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Cliente implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   private int codigo;
   private String nome;
   private String endereco;
   private String telefone;

   public String toString() {
      return String
            .format("%20s%20s%20s%20s", codigo, nome, endereco, telefone);
   }

   public int getCodigo() {
      return codigo;
   }

   public void setCodigo(int codigo) {
      this.codigo = codigo;
   }

   public String getNome() {
      return nome;
   }

   public void setNome(String nome) {
      this.nome = nome;
   }

   public String getEndereco() {
      return endereco;
   }

   public void setEndereco(String endereco) {
      this.endereco = endereco;
   }

   public String getTelefone() {
      return telefone;
   }

   public void setTelefone(String telefone) {
      this.telefone = telefone;
   }
}


Criando o Session Bean
Interface Remota
package teste;

import java.util.List;

import javax.ejb.Remote;

@Remote
public interface ClienteBean {
   void inserir(Cliente cliente);

   List<Cliente> listar();
}


Implementação
package teste;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless(name = "cli", mappedName = "ejb/ClienteBean")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class ClienteBeanImpl implements ClienteBean {
   @PersistenceContext(unitName = "bean1")
   private EntityManager em;

   public void inserir(Cliente cliente) {
      em.persist(cliente);
   }

   @TransactionAttribute(TransactionAttributeType.NEVER)
   public List<Cliente> listar() {
      Query query = em.createQuery("select c from Cliente c");
      return query.getResultList();
   }
}


Cliente do EJB
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import teste.Cliente;
import teste.ClienteBean;

public class Consumo {
   public static void main(String[] args) {
      if (args.length == 0) {
         System.out.println("Qtd de parametros incorreta");
         System.exit(0);
      }
      int codigo = new Integer(args[0]);
      try {
         Properties props = new Properties();
         props.setProperty("java.naming.factory.initial",
               "com.sun.enterprise.naming.SerialInitContextFactory");
         props.setProperty("java.naming.factory.url.pkgs",
               "com.sun.enterprise.naming");
         props.setProperty("java.naming.factory.state",
               "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
         // optional. Defaults to localhost. Only needed if web server is
         // running
         // on a different host than the appserver
         props.setProperty("org.omg.CORBA.ORBInitialHost""10.0.0.100");
         // optional. Defaults to 3700. Only needed if target orb port is not
         // 3700.
         props.setProperty("org.omg.CORBA.ORBInitialPort""3700");
         InitialContext ctx = new InitialContext(props);
         ClienteBean bean = (ClienteBeanctx.lookup("ejb/ClienteBean");
         Cliente cliente = new Cliente();
         cliente.setCodigo(codigo);
         cliente.setNome("antonio");
         cliente.setEndereco("Rua 2");
         cliente.setTelefone("6363-5252");
         bean.inserir(cliente);
         List<Cliente> lista = bean.listar();
         for (Cliente c : lista) {
            System.out.println(c);
         }
      catch (NamingException e) {
         e.printStackTrace();
      }
   }
}


Relação de .jar
Arquivos .jar necessários:

No ejb:
  • appserv-rt.jar
  • javaee.jar

No cliente:
  • appserv-rt.jar
  • javaee.jar
  • appserv-deployment-client.jar

Iniciando ao JavaDB (Derby)

  • Passo 1
ligue o servidor com o comando: java -jar derbynet.jar start
  • Passo 2
dados para conexão:
url: jdbc:derby://localhost:1527/exemplojpa;create=true
driver: org.apache.derby.jdbc.ClientDriver

arquivo driver: derbyclient.jar

Propriedades da JPA

DataSource
referencia a um datasource:

<jta-data-source>java:comp/env/jdbc/simenet</jta-data-source> 


referencia a um datasource no tomcat (fora da JTA): Com HIBERNATE

<non-jta-data-source>java:comp/env/jdbc/simenet</non-jta-data-source> 

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
             version="1.0">
    <persistence-unit name="default">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.connection.url" value="jdbc:hsqldb:."/>
            <property name="hibernate.max_fetch_depth" value="3"/>
        </properties>
    </persistence-unit>
</persistence>


Com TOPLINK
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
        <persistence-unit name="default">
                <provider>oracle.toplink.essentials.PersistenceProvider</provider>
                <exclude-unlisted-classes>false</exclude-unlisted-classes>
                <properties>
                        <property name="toplink.ddl-generation" value="drop-and-create-tables" />
                        <property name="toplink.logging.level" value="FINE" />
                        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost/myDB" />
                        <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver" />
                        <property name="toplink.jdbc.user" value="root" />
                        <property name="toplink.jdbc.password" value="" />
                </properties>
        </persistence-unit>
</persistence>


Configuração do TopLink para funcionamento com datasource no tomcat:


import oracle.toplink.essentials.jndi.JNDIConnector;
import oracle.toplink.essentials.sessions.Session;
import oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer;

public class ToplinkSessionCustomizer implements SessionCustomizer {
  public void customize(Session sessionthrows Exception {
    JNDIConnector connector = (JNDIConnectorsession.getLogin()
        .getConnector();
    connector.setLookupType(JNDIConnector.STRING_LOOKUP);
  }
}

linha a ser acrescientada nas properties:

<property name="toplink.session.customizer" value="pacote.ToplinkSessionCustomizer"/>
veja link: http://forums.oracle.com/forums/thread.jspa?messageID=1899677